Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--source/application/StarMainApplication_sdl.cpp22
-rw-r--r--source/application/StarP2PNetworkingService_pc.cpp98
-rw-r--r--source/application/StarPlatformServices_pc.cpp18
-rw-r--r--source/application/StarRenderer_opengl20.cpp22
-rw-r--r--source/application/StarStatisticsService_pc_steam.cpp8
-rw-r--r--source/base/StarAnimatedPartSet.cpp2
-rw-r--r--source/base/StarAssets.cpp72
-rw-r--r--source/base/StarDirectoryAssetSource.cpp4
-rw-r--r--source/base/StarPackedAssetSource.cpp4
-rw-r--r--source/base/StarVersionOptionParser.cpp6
-rw-r--r--source/client/StarClientApplication.cpp34
-rw-r--r--source/core/StarAudio.cpp12
-rw-r--r--source/core/StarBTreeDatabase.cpp14
-rw-r--r--source/core/StarBiMap.hpp6
-rw-r--r--source/core/StarBuffer.cpp4
-rw-r--r--source/core/StarByteArray.cpp4
-rw-r--r--source/core/StarByteArray.hpp2
-rw-r--r--source/core/StarCasting.hpp4
-rw-r--r--source/core/StarColor.cpp4
-rw-r--r--source/core/StarCompression.cpp16
-rw-r--r--source/core/StarException_unix.cpp10
-rw-r--r--source/core/StarException_windows.cpp6
-rw-r--r--source/core/StarFile.cpp4
-rw-r--r--source/core/StarFile_unix.cpp34
-rw-r--r--source/core/StarFile_windows.cpp54
-rw-r--r--source/core/StarFont.cpp2
-rw-r--r--source/core/StarFormattedJson.cpp34
-rw-r--r--source/core/StarHostAddress.cpp10
-rw-r--r--source/core/StarIODevice.cpp4
-rw-r--r--source/core/StarIdMap.hpp2
-rw-r--r--source/core/StarImage.cpp20
-rw-r--r--source/core/StarImageProcessing.cpp40
-rw-r--r--source/core/StarJson.cpp32
-rw-r--r--source/core/StarJsonBuilder.cpp2
-rw-r--r--source/core/StarJsonBuilder.hpp8
-rw-r--r--source/core/StarJsonExtra.cpp8
-rw-r--r--source/core/StarJsonExtra.hpp12
-rw-r--r--source/core/StarJsonPatch.cpp12
-rw-r--r--source/core/StarJsonPath.cpp10
-rw-r--r--source/core/StarJsonPath.hpp26
-rw-r--r--source/core/StarJsonRpc.cpp12
-rw-r--r--source/core/StarLexicalCast.hpp2
-rw-r--r--source/core/StarList.hpp4
-rw-r--r--source/core/StarLockFile_unix.cpp4
-rw-r--r--source/core/StarLockFile_windows.cpp2
-rw-r--r--source/core/StarLogging.cpp4
-rw-r--r--source/core/StarLogging.hpp2
-rw-r--r--source/core/StarLua.cpp8
-rw-r--r--source/core/StarLua.hpp18
-rw-r--r--source/core/StarMap.hpp10
-rw-r--r--source/core/StarMultiArray.hpp6
-rw-r--r--source/core/StarNetElementContainers.hpp4
-rw-r--r--source/core/StarNetImpl.hpp4
-rw-r--r--source/core/StarOptionParser.cpp48
-rw-r--r--source/core/StarOrderedMap.hpp16
-rw-r--r--source/core/StarSignalHandler_windows.cpp8
-rw-r--r--source/core/StarSmallVector.hpp6
-rw-r--r--source/core/StarSocket.cpp20
-rw-r--r--source/core/StarStaticVector.hpp8
-rw-r--r--source/core/StarString.cpp4
-rw-r--r--source/core/StarString.hpp2
-rw-r--r--source/core/StarStringView.cpp4
-rw-r--r--source/core/StarTcp.cpp16
-rw-r--r--source/core/StarThread_unix.cpp16
-rw-r--r--source/core/StarThread_windows.cpp6
-rw-r--r--source/core/StarTime.cpp8
-rw-r--r--source/core/StarTime_unix.cpp14
-rw-r--r--source/core/StarTime_windows.cpp14
-rw-r--r--source/core/StarUdp.cpp6
-rw-r--r--source/core/StarUnicode.cpp2
-rw-r--r--source/core/StarUuid.cpp2
-rw-r--r--source/core/StarWorkerPool.cpp2
-rw-r--r--source/frontend/StarActionBar.cpp20
-rw-r--r--source/frontend/StarBookmarkInterface.cpp4
-rw-r--r--source/frontend/StarCharCreation.cpp12
-rw-r--r--source/frontend/StarChat.cpp6
-rw-r--r--source/frontend/StarCinematic.cpp2
-rw-r--r--source/frontend/StarClientCommandProcessor.cpp42
-rw-r--r--source/frontend/StarCodexInterface.cpp2
-rw-r--r--source/frontend/StarContainerInterface.cpp2
-rw-r--r--source/frontend/StarCraftingInterface.cpp10
-rw-r--r--source/frontend/StarGraphicsMenu.cpp4
-rw-r--r--source/frontend/StarInventory.cpp22
-rw-r--r--source/frontend/StarItemTooltip.cpp22
-rw-r--r--source/frontend/StarKeybindingsMenu.cpp2
-rw-r--r--source/frontend/StarMainInterface.cpp12
-rw-r--r--source/frontend/StarMerchantInterface.cpp10
-rw-r--r--source/frontend/StarQuestInterface.cpp4
-rw-r--r--source/frontend/StarRadioMessagePopup.cpp6
-rw-r--r--source/frontend/StarScriptPane.cpp2
-rw-r--r--source/frontend/StarTeamBar.cpp4
-rw-r--r--source/frontend/StarTeleportDialog.cpp2
-rw-r--r--source/frontend/StarWidgetLuaBindings.cpp2
-rw-r--r--source/game/StarActorMovementController.cpp8
-rw-r--r--source/game/StarAiDatabase.cpp2
-rw-r--r--source/game/StarBehaviorDatabase.cpp18
-rw-r--r--source/game/StarBehaviorState.cpp12
-rw-r--r--source/game/StarBiomeDatabase.cpp10
-rw-r--r--source/game/StarBiomePlacement.cpp4
-rw-r--r--source/game/StarCelestialCoordinate.cpp14
-rw-r--r--source/game/StarCelestialDatabase.cpp16
-rw-r--r--source/game/StarCelestialGraphics.cpp12
-rw-r--r--source/game/StarCelestialParameters.cpp2
-rw-r--r--source/game/StarChatProcessor.cpp12
-rw-r--r--source/game/StarCodexDatabase.cpp4
-rw-r--r--source/game/StarCollectionDatabase.cpp6
-rw-r--r--source/game/StarCommandProcessor.cpp108
-rw-r--r--source/game/StarDamageDatabase.cpp8
-rw-r--r--source/game/StarDanceDatabase.cpp2
-rw-r--r--source/game/StarDungeonGenerator.cpp44
-rw-r--r--source/game/StarDungeonImagePart.cpp6
-rw-r--r--source/game/StarDungeonTMXPart.cpp8
-rw-r--r--source/game/StarEffectSourceDatabase.cpp4
-rw-r--r--source/game/StarEntityFactory.cpp8
-rw-r--r--source/game/StarEntityMap.cpp10
-rw-r--r--source/game/StarForceRegions.cpp2
-rw-r--r--source/game/StarGameTypes.cpp2
-rw-r--r--source/game/StarHumanoid.cpp120
-rw-r--r--source/game/StarInventoryTypes.cpp6
-rw-r--r--source/game/StarItem.cpp2
-rw-r--r--source/game/StarItemDatabase.cpp28
-rw-r--r--source/game/StarItemDescriptor.cpp2
-rw-r--r--source/game/StarLiquidsDatabase.cpp14
-rw-r--r--source/game/StarMaterialDatabase.cpp32
-rw-r--r--source/game/StarMaterialRenderProfile.cpp6
-rw-r--r--source/game/StarMicroDungeon.cpp4
-rw-r--r--source/game/StarMonster.cpp2
-rw-r--r--source/game/StarMonsterDatabase.cpp18
-rw-r--r--source/game/StarNameGenerator.cpp8
-rw-r--r--source/game/StarNetPacketSocket.cpp14
-rw-r--r--source/game/StarNetPackets.cpp2
-rw-r--r--source/game/StarNetworkedAnimator.cpp2
-rw-r--r--source/game/StarNpcDatabase.cpp4
-rw-r--r--source/game/StarObject.cpp4
-rw-r--r--source/game/StarObjectDatabase.cpp12
-rw-r--r--source/game/StarParallax.cpp6
-rw-r--r--source/game/StarParticleDatabase.cpp4
-rw-r--r--source/game/StarPlant.cpp32
-rw-r--r--source/game/StarPlantDatabase.cpp14
-rw-r--r--source/game/StarPlatformerAStarTypes.hpp4
-rw-r--r--source/game/StarPlayer.cpp4
-rw-r--r--source/game/StarPlayerCodexes.cpp4
-rw-r--r--source/game/StarPlayerStorage.cpp38
-rw-r--r--source/game/StarPlayerTech.cpp4
-rw-r--r--source/game/StarProjectile.cpp6
-rw-r--r--source/game/StarProjectileDatabase.cpp14
-rw-r--r--source/game/StarQuestDescriptor.cpp4
-rw-r--r--source/game/StarQuestManager.cpp2
-rw-r--r--source/game/StarQuestTemplateDatabase.cpp4
-rw-r--r--source/game/StarQuests.cpp2
-rw-r--r--source/game/StarRadioMessageDatabase.cpp8
-rw-r--r--source/game/StarRoot.cpp26
-rw-r--r--source/game/StarRootLoader.cpp10
-rw-r--r--source/game/StarServerClientContext.cpp2
-rw-r--r--source/game/StarSongbook.cpp10
-rw-r--r--source/game/StarSpawnTypeDatabase.cpp6
-rw-r--r--source/game/StarSpawner.cpp8
-rw-r--r--source/game/StarSpeciesDatabase.cpp4
-rw-r--r--source/game/StarStagehandDatabase.cpp4
-rw-r--r--source/game/StarStatSet.cpp22
-rw-r--r--source/game/StarStatistics.cpp10
-rw-r--r--source/game/StarStatisticsDatabase.cpp8
-rw-r--r--source/game/StarStatusController.cpp2
-rw-r--r--source/game/StarStatusEffectDatabase.cpp4
-rw-r--r--source/game/StarStoredFunctions.cpp14
-rw-r--r--source/game/StarSystemWorld.cpp2
-rw-r--r--source/game/StarSystemWorldServer.cpp8
-rw-r--r--source/game/StarSystemWorldServerThread.cpp6
-rw-r--r--source/game/StarTechController.cpp2
-rw-r--r--source/game/StarTechDatabase.cpp6
-rw-r--r--source/game/StarTenantDatabase.cpp8
-rw-r--r--source/game/StarTerrainDatabase.cpp8
-rw-r--r--source/game/StarTilesetDatabase.cpp2
-rw-r--r--source/game/StarTreasure.cpp18
-rw-r--r--source/game/StarUniverseClient.cpp10
-rw-r--r--source/game/StarUniverseConnection.cpp14
-rw-r--r--source/game/StarUniverseServer.cpp152
-rw-r--r--source/game/StarUniverseSettings.cpp6
-rw-r--r--source/game/StarVehicleDatabase.cpp6
-rw-r--r--source/game/StarVersioningDatabase.cpp22
-rw-r--r--source/game/StarWarping.cpp14
-rw-r--r--source/game/StarWireProcessor.cpp2
-rw-r--r--source/game/StarWorldClient.cpp12
-rw-r--r--source/game/StarWorldGeneration.cpp16
-rw-r--r--source/game/StarWorldLayout.cpp22
-rw-r--r--source/game/StarWorldParameters.cpp2
-rw-r--r--source/game/StarWorldServer.cpp22
-rw-r--r--source/game/StarWorldServerThread.cpp22
-rw-r--r--source/game/StarWorldStorage.cpp10
-rw-r--r--source/game/StarWorldStructure.cpp2
-rw-r--r--source/game/StarWorldTiles.cpp2
-rw-r--r--source/game/interfaces/StarBeamItem.cpp2
-rw-r--r--source/game/items/StarMaterialItem.cpp2
-rw-r--r--source/game/items/StarObjectItem.cpp2
-rw-r--r--source/game/items/StarTools.cpp6
-rw-r--r--source/game/items/StarUnlockItem.cpp2
-rw-r--r--source/game/objects/StarContainerObject.cpp2
-rw-r--r--source/game/scripting/StarLuaComponents.cpp8
-rw-r--r--source/game/scripting/StarLuaComponents.hpp6
-rw-r--r--source/game/scripting/StarLuaRoot.cpp6
-rw-r--r--source/game/scripting/StarWorldLuaBindings.cpp52
-rw-r--r--source/json_tool/editor_gui.cpp2
-rw-r--r--source/json_tool/json_tool.cpp32
-rw-r--r--source/mod_uploader/StarModUploader.cpp12
-rw-r--r--source/mod_uploader/main.cpp4
-rw-r--r--source/rendering/StarTextPainter.cpp2
-rw-r--r--source/rendering/StarTilePainter.cpp2
-rw-r--r--source/server/StarServerQueryThread.cpp2
-rw-r--r--source/server/StarServerRconClient.cpp12
-rw-r--r--source/server/StarServerRconThread.cpp2
-rw-r--r--source/server/main.cpp2
-rw-r--r--source/test/spawn_test.cpp2
-rw-r--r--source/test/string_test.cpp4
-rw-r--r--source/utility/asset_packer.cpp18
-rw-r--r--source/utility/asset_unpacker.cpp10
-rw-r--r--source/utility/dump_versioned_json.cpp4
-rw-r--r--source/utility/dungeon_generation_benchmark.cpp14
-rw-r--r--source/utility/fix_embedded_tilesets.cpp6
-rw-r--r--source/utility/game_repl.cpp4
-rw-r--r--source/utility/generation_benchmark.cpp10
-rw-r--r--source/utility/make_versioned_json.cpp4
-rw-r--r--source/utility/map_grep.cpp6
-rw-r--r--source/utility/planet_mapgen.cpp6
-rw-r--r--source/utility/render_terrain_selector.cpp4
-rw-r--r--source/utility/tileset_updater.cpp18
-rw-r--r--source/utility/update_tilesets.cpp6
-rw-r--r--source/utility/word_count.cpp8
-rw-r--r--source/utility/world_benchmark.cpp10
-rw-r--r--source/windowing/StarFuelWidget.cpp2
-rw-r--r--source/windowing/StarGuiReader.cpp6
-rw-r--r--source/windowing/StarGuiTypes.cpp2
-rw-r--r--source/windowing/StarItemGridWidget.cpp2
-rw-r--r--source/windowing/StarItemSlotWidget.cpp6
-rw-r--r--source/windowing/StarKeyBindings.cpp8
-rw-r--r--source/windowing/StarListWidget.cpp8
-rw-r--r--source/windowing/StarRegisteredPaneManager.hpp8
-rw-r--r--source/windowing/StarSliderBar.cpp18
-rw-r--r--source/windowing/StarWidget.cpp18
-rw-r--r--source/windowing/StarWidgetParsing.cpp54
239 files changed, 1432 insertions, 1432 deletions
diff --git a/source/application/StarMainApplication_sdl.cpp b/source/application/StarMainApplication_sdl.cpp
index 45e224d..8c05508 100644
--- a/source/application/StarMainApplication_sdl.cpp
+++ b/source/application/StarMainApplication_sdl.cpp
@@ -212,7 +212,7 @@ public:
Logger::info("Application: Initializing SDL");
if (SDL_Init(0))
- throw ApplicationException(strf("Couldn't initialize SDL: %s", SDL_GetError()));
+ throw ApplicationException(strf("Couldn't initialize SDL: {}", SDL_GetError()));
if (char* basePath = SDL_GetBasePath()) {
File::changeDirectory(basePath);
@@ -231,15 +231,15 @@ public:
Logger::info("Application: Initializing SDL Video");
if (SDL_InitSubSystem(SDL_INIT_VIDEO))
- throw ApplicationException(strf("Couldn't initialize SDL Video: %s", SDL_GetError()));
+ throw ApplicationException(strf("Couldn't initialize SDL Video: {}", SDL_GetError()));
Logger::info("Application: Initializing SDL Joystick");
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK))
- throw ApplicationException(strf("Couldn't initialize SDL Joystick: %s", SDL_GetError()));
+ throw ApplicationException(strf("Couldn't initialize SDL Joystick: {}", SDL_GetError()));
Logger::info("Application: Initializing SDL Sound");
if (SDL_InitSubSystem(SDL_INIT_AUDIO))
- throw ApplicationException(strf("Couldn't initialize SDL Sound: %s", SDL_GetError()));
+ throw ApplicationException(strf("Couldn't initialize SDL Sound: {}", SDL_GetError()));
SDL_JoystickEventState(SDL_ENABLE);
@@ -251,7 +251,7 @@ public:
m_sdlWindow = SDL_CreateWindow(m_windowTitle.utf8Ptr(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
m_windowSize[0], m_windowSize[1], SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!m_sdlWindow)
- throw ApplicationException::format("Application: Could not create SDL window: %s", SDL_GetError());
+ throw ApplicationException::format("Application: Could not create SDL window: {}", SDL_GetError());
SDL_ShowWindow(m_sdlWindow);
SDL_RaiseWindow(m_sdlWindow);
@@ -263,7 +263,7 @@ public:
m_sdlGlContext = SDL_GL_CreateContext(m_sdlWindow);
if (!m_sdlGlContext)
- throw ApplicationException::format("Application: Could not create OpenGL context: %s", SDL_GetError());
+ throw ApplicationException::format("Application: Could not create OpenGL context: {}", SDL_GetError());
SDL_GL_SwapWindow(m_sdlWindow);
setVSyncEnabled(m_windowVSync);
@@ -288,7 +288,7 @@ public:
SDL_CloseAudioDevice(m_sdlAudioDevice);
Logger::error("Application: Could not open 44.1khz / 16 bit stereo audio device, no sound available!");
} else {
- Logger::info("Application: Opened default audio device with 44.1khz / 16 bit stereo audio, %s sample size buffer", obtained.samples);
+ Logger::info("Application: Opened default audio device with 44.1khz / 16 bit stereo audio, {} sample size buffer", obtained.samples);
SDL_PauseAudioDevice(m_sdlAudioDevice, 0);
}
@@ -375,14 +375,14 @@ public:
Thread::sleepPrecise(spareMilliseconds);
}
} catch (std::exception const& e) {
- Logger::error("Application: exception thrown, shutting down: %s", outputException(e, true));
+ Logger::error("Application: exception thrown, shutting down: {}", outputException(e, true));
}
try {
Logger::info("Application: shutdown...");
m_application->shutdown();
} catch (std::exception const& e) {
- Logger::error("Application: threw exception during shutdown: %s", outputException(e, true));
+ Logger::error("Application: threw exception during shutdown: {}", outputException(e, true));
}
SDL_CloseAudioDevice(m_sdlAudioDevice);
@@ -432,10 +432,10 @@ private:
parent->m_windowMode = WindowMode::Fullscreen;
SDL_SetWindowFullscreen(parent->m_sdlWindow, SDL_WINDOW_FULLSCREEN);
} else {
- Logger::warn("Failed to set resolution %s, %s", (unsigned)requestedDisplayMode.w, (unsigned)requestedDisplayMode.h);
+ Logger::warn("Failed to set resolution {}, {}", (unsigned)requestedDisplayMode.w, (unsigned)requestedDisplayMode.h);
}
} else {
- Logger::warn("Unable to set requested display resolution %s, %s", (int)fullScreenResolution[0], (int)fullScreenResolution[1]);
+ Logger::warn("Unable to set requested display resolution {}, {}", (int)fullScreenResolution[0], (int)fullScreenResolution[1]);
}
SDL_DisplayMode actualDisplayMode;
diff --git a/source/application/StarP2PNetworkingService_pc.cpp b/source/application/StarP2PNetworkingService_pc.cpp
index 2a0b876..74c48ac 100644
--- a/source/application/StarP2PNetworkingService_pc.cpp
+++ b/source/application/StarP2PNetworkingService_pc.cpp
@@ -32,13 +32,13 @@ PcP2PNetworkingService::PcP2PNetworkingService(PcPlatformServicesStatePtr state)
m_discordOnActivityJoinToken = m_state->discordCore->ActivityManager().OnActivityJoin.Connect([this](char const* peerId) {
MutexLocker serviceLocker(m_mutex);
- Logger::info("Joining discord peer at '%s'", peerId);
- addPendingJoin(strf("+platform:%s", peerId));
+ Logger::info("Joining discord peer at '{}'", peerId);
+ addPendingJoin(strf("+platform:{}", peerId));
});
m_discordOnActivityRequestToken = m_state->discordCore->ActivityManager().OnActivityJoinRequest.Connect([this](discord::User const& user) {
MutexLocker serviceLocker(m_mutex);
String userName = String(user.GetUsername());
- Logger::info("Received join request from user '%s'", userName);
+ Logger::info("Received join request from user '{}'", userName);
m_discordJoinRequests.emplace_back(make_pair(user.GetId(), userName));
});
m_discordOnReceiveMessage = m_state->discordCore->LobbyManager().OnNetworkMessage.Connect(bind(&PcP2PNetworkingService::discordOnReceiveMessage, this, _1, _2, _3, _4, _5));
@@ -54,9 +54,9 @@ PcP2PNetworkingService::~PcP2PNetworkingService() {
if (m_state->discordAvailable) {
MutexLocker discordLocker(m_state->discordMutex);
if (m_discordServerLobby) {
- Logger::info("Deleting discord server lobby %s", m_discordServerLobby->first);
+ Logger::info("Deleting discord server lobby {}", m_discordServerLobby->first);
m_state->discordCore->LobbyManager().DeleteLobby(m_discordServerLobby->first, [](discord::Result res) {
- Logger::error("Could not connect delete server lobby (err %s)", (int)res);
+ Logger::error("Could not connect delete server lobby (err {})", (int)res);
});
}
@@ -108,18 +108,18 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, Maybe<pa
}
if (auto lobby = m_discordServerLobby)
- activity.GetParty().SetId(strf("%s", lobby->first).c_str());
+ activity.GetParty().SetId(strf("{}", lobby->first).c_str());
if (m_joinLocation.is<JoinLocal>()) {
if (auto lobby = m_discordServerLobby) {
- String joinSecret = strf("connect:discord_%s_%s_%s", m_state->discordCurrentUser->GetId(), lobby->first, lobby->second);
- Logger::info("Setting discord join secret as %s", joinSecret);
+ String joinSecret = strf("connect:discord_{}_{}_{}", m_state->discordCurrentUser->GetId(), lobby->first, lobby->second);
+ Logger::info("Setting discord join secret as {}", joinSecret);
activity.GetSecrets().SetJoin(joinSecret.utf8Ptr());
}
} else if (m_joinLocation.is<JoinRemote>()) {
- String address = strf("%s", (HostAddressWithPort)m_joinLocation.get<JoinRemote>());
- String joinSecret = strf("connect:address_%s", address);
- Logger::info("Setting discord join secret as %s", joinSecret);
+ String address = strf("{}", (HostAddressWithPort)m_joinLocation.get<JoinRemote>());
+ String joinSecret = strf("connect:address_{}", address);
+ Logger::info("Setting discord join secret as {}", joinSecret);
activity.GetSecrets().SetJoin(joinSecret.utf8Ptr());
activity.GetParty().SetId(address.utf8Ptr());
@@ -128,7 +128,7 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, Maybe<pa
m_discordUpdatingActivity = true;
m_state->discordCore->ActivityManager().UpdateActivity(activity, [this](discord::Result res) {
if (res != discord::Result::Ok)
- Logger::error("failed to set discord activity (err %s)", (int)res);
+ Logger::error("failed to set discord activity (err {})", (int)res);
MutexLocker serviceLocker(m_mutex);
m_discordUpdatingActivity = false;
@@ -193,7 +193,7 @@ void Star::PcP2PNetworkingService::update() {
m_state->discordCore->ActivityManager().SendRequestReply(p.first, reply, [](discord::Result res) {
if (res != discord::Result::Ok)
- Logger::error("Could not send discord activity join response (err %s)", (int)res);
+ Logger::error("Could not send discord activity join response (err {})", (int)res);
});
}
}
@@ -230,17 +230,17 @@ Either<String, P2PSocketUPtr> PcP2PNetworkingService::connectToPeer(P2PNetworkin
}
#endif
- return makeLeft(strf("Unsupported peer type '%s'", type));
+ return makeLeft(strf("Unsupported peer type '{}'", type));
}
void PcP2PNetworkingService::addPendingJoin(String connectionString) {
MutexLocker serviceLocker(m_mutex);
if (connectionString.extract(":") != "+platform")
- throw ApplicationException::format("malformed connection string '%s'", connectionString);
+ throw ApplicationException::format("malformed connection string '{}'", connectionString);
if (connectionString.extract(":") != "connect")
- throw ApplicationException::format("malformed connection string '%s'", connectionString);
+ throw ApplicationException::format("malformed connection string '{}'", connectionString);
String target = move(connectionString);
String targetType = target.extract("_");
@@ -248,7 +248,7 @@ void PcP2PNetworkingService::addPendingJoin(String connectionString) {
if (targetType == "address")
m_pendingJoin = HostAddressWithPort(target);
else
- m_pendingJoin = P2PNetworkingPeerId(strf("%s_%s", targetType, target));
+ m_pendingJoin = P2PNetworkingPeerId(strf("{}_{}", targetType, target));
}
#ifdef STAR_ENABLE_STEAM_INTEGRATION
@@ -312,7 +312,7 @@ auto PcP2PNetworkingService::createSteamP2PSocket(CSteamID steamId) -> unique_pt
void PcP2PNetworkingService::steamOnConnectionFailure(P2PSessionConnectFail_t* callback) {
MutexLocker serviceLocker(m_mutex);
- Logger::warn("Connection with steam user %s failed", callback->m_steamIDRemote.ConvertToUint64());
+ Logger::warn("Connection with steam user {} failed", callback->m_steamIDRemote.ConvertToUint64());
if (auto socket = m_steamOpenSockets.value(callback->m_steamIDRemote.ConvertToUint64())) {
MutexLocker socketLocker(socket->mutex);
steamCloseSocket(socket);
@@ -320,7 +320,7 @@ void PcP2PNetworkingService::steamOnConnectionFailure(P2PSessionConnectFail_t* c
}
void PcP2PNetworkingService::steamOnJoinRequested(GameRichPresenceJoinRequested_t* callback) {
- Logger::info("Queueing join request with steam friend id %s to address %s", callback->m_steamIDFriend.ConvertToUint64(), callback->m_rgchConnect);
+ Logger::info("Queueing join request with steam friend id {} to address {}", callback->m_steamIDFriend.ConvertToUint64(), callback->m_rgchConnect);
addPendingJoin(callback->m_rgchConnect);
}
@@ -330,19 +330,19 @@ void PcP2PNetworkingService::steamOnSessionRequest(P2PSessionRequest_t* callback
// non-friends can even initiate P2P sessions.
if (m_acceptingP2PConnections && SteamFriends()->HasFriend(callback->m_steamIDRemote, k_EFriendFlagImmediate)) {
if (SteamNetworking()->AcceptP2PSessionWithUser(callback->m_steamIDRemote)) {
- Logger::info("Accepted steam p2p connection with user %s", callback->m_steamIDRemote.ConvertToUint64());
+ Logger::info("Accepted steam p2p connection with user {}", callback->m_steamIDRemote.ConvertToUint64());
m_pendingIncomingConnections.append(createSteamP2PSocket(callback->m_steamIDRemote));
} else {
- Logger::error("Accepting steam p2p connection from user %s failed!", callback->m_steamIDRemote.ConvertToUint64());
+ Logger::error("Accepting steam p2p connection from user {} failed!", callback->m_steamIDRemote.ConvertToUint64());
}
} else {
- Logger::error("Ignoring steam p2p connection from user %s", callback->m_steamIDRemote.ConvertToUint64());
+ Logger::error("Ignoring steam p2p connection from user {}", callback->m_steamIDRemote.ConvertToUint64());
}
}
void PcP2PNetworkingService::steamCloseSocket(SteamP2PSocket* socket) {
if (socket->connected) {
- Logger::info("Closing p2p connection with steam user %s", socket->steamId.ConvertToUint64());
+ Logger::info("Closing p2p connection with steam user {}", socket->steamId.ConvertToUint64());
m_steamOpenSockets.remove(socket->steamId.ConvertToUint64());
socket->connected = false;
}
@@ -386,7 +386,7 @@ bool PcP2PNetworkingService::DiscordP2PSocket::sendMessage(ByteArray const& mess
discord::Result res = parent->m_state->discordCore->LobbyManager().SendNetworkMessage(lobbyId, remoteUserId, DiscordMainNetworkChannel, (uint8_t*)message.ptr(), message.size());
if (res != discord::Result::Ok)
- throw ApplicationException::format("discord::Network::Send returned error (err %s)", (int)res);
+ throw ApplicationException::format("discord::Network::Send returned error (err {})", (int)res);
return true;
}
@@ -407,13 +407,13 @@ void PcP2PNetworkingService::discordCloseSocket(DiscordP2PSocket* socket) {
if (!m_joinLocation.is<JoinLocal>() && m_discordOpenSockets.empty()) {
auto res = m_state->discordCore->LobbyManager().DisconnectNetwork(socket->lobbyId);
if (res != discord::Result::Ok)
- Logger::error("failed to leave network for lobby %s (err %s)", socket->lobbyId, (int)res);
+ Logger::error("failed to leave network for lobby {} (err {})", socket->lobbyId, (int)res);
m_state->discordCore->LobbyManager().DisconnectLobby(socket->lobbyId, [this, lobbyId = socket->lobbyId](discord::Result res) {
if (res != discord::Result::Ok)
- Logger::error("failed to leave discord lobby %s", lobbyId);
+ Logger::error("failed to leave discord lobby {}", lobbyId);
- Logger::info("Left discord lobby %s", lobbyId);
+ Logger::info("Left discord lobby {}", lobbyId);
MutexLocker serviceLocker(m_mutex);
m_discordServerLobby = {};
m_discordForceUpdateActivity = true;
@@ -438,7 +438,7 @@ P2PSocketUPtr PcP2PNetworkingService::discordConnectRemote(discord::UserId remot
socket->lobbyId = lobbyId;
m_discordOpenSockets[remoteUserId] = socket.get();
- Logger::info("Connect to discord lobby %s", lobbyId);
+ Logger::info("Connect to discord lobby {}", lobbyId);
m_state->discordCore->LobbyManager().ConnectLobby(lobbyId, lobbySecret.utf8Ptr(), [this, remoteUserId, lobbyId](discord::Result res, discord::Lobby const& lobby) {
MutexLocker serviceLocker(m_mutex);
if (res == discord::Result::Ok) {
@@ -448,25 +448,25 @@ P2PSocketUPtr PcP2PNetworkingService::discordConnectRemote(discord::UserId remot
res = m_state->discordCore->LobbyManager().ConnectNetwork(lobbyId);
if (res != discord::Result::Ok) {
discordCloseSocket(socket);
- return Logger::error("Could not connect to discord lobby network (err %s)", (int)res);
+ return Logger::error("Could not connect to discord lobby network (err {})", (int)res);
}
res = m_state->discordCore->LobbyManager().OpenNetworkChannel(lobbyId, DiscordMainNetworkChannel, true);
if (res != discord::Result::Ok) {
discordCloseSocket(socket);
- return Logger::error("Could not open discord main network channel (err %s)", (int)res);
+ return Logger::error("Could not open discord main network channel (err {})", (int)res);
}
socket->mode = DiscordSocketMode::Connected;
- Logger::info("Discord p2p connection opened to remote user %s via lobby %s", remoteUserId, lobbyId);
+ Logger::info("Discord p2p connection opened to remote user {} via lobby {}", remoteUserId, lobbyId);
m_discordServerLobby = make_pair(lobbyId, String());
m_discordForceUpdateActivity = true;
} else {
- Logger::error("discord::Lobbies::Connect callback no matching remoteUserId %s found", remoteUserId);
+ Logger::error("discord::Lobbies::Connect callback no matching remoteUserId {} found", remoteUserId);
}
} else {
- Logger::error("failed to connect to remote lobby (err %s)", (int)res);
+ Logger::error("failed to connect to remote lobby (err {})", (int)res);
if (auto socket = m_discordOpenSockets.value(remoteUserId)) {
MutexLocker socketLocker(socket->mutex);
discordCloseSocket(socket);
@@ -481,17 +481,17 @@ void PcP2PNetworkingService::discordOnReceiveMessage(discord::LobbyId lobbyId, d
MutexLocker serviceLocker(m_mutex);
if (lobbyId != m_discordServerLobby->first)
- return Logger::error("Received message from unexpected lobby %s", lobbyId);
+ return Logger::error("Received message from unexpected lobby {}", lobbyId);
if (auto socket = m_discordOpenSockets.value(userId)) {
if (channel == DiscordMainNetworkChannel) {
MutexLocker socketLocker(socket->mutex);
socket->incoming.append(ByteArray((char const*)data, size));
} else {
- Logger::error("Received discord message on unexpected channel %s, ignoring", channel);
+ Logger::error("Received discord message on unexpected channel {}, ignoring", channel);
}
} else {
- Logger::error("Could not find associated discord socket for user id %s", userId);
+ Logger::error("Could not find associated discord socket for user id {}", userId);
}
}
@@ -508,7 +508,7 @@ void PcP2PNetworkingService::discordOnLobbyMemberConnect(discord::LobbyId lobbyI
m_discordOpenSockets[userId] = socket.get();
m_pendingIncomingConnections.append(move(socket));
- Logger::info("Accepted new discord connection from remote user %s", userId);
+ Logger::info("Accepted new discord connection from remote user {}", userId);
}
}
}
@@ -548,13 +548,13 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) {
} else if (m_joinLocation.is<JoinLocal>()) {
auto steamId = SteamUser()->GetSteamID().ConvertToUint64();
- Logger::info("Setting steam rich presence connection as steamid_%s", steamId);
- SteamFriends()->SetRichPresence("connect", strf("+platform:connect:steamid_%s", steamId).c_str());
+ Logger::info("Setting steam rich presence connection as steamid_{}", steamId);
+ SteamFriends()->SetRichPresence("connect", strf("+platform:connect:steamid_{}", steamId).c_str());
} else if (m_joinLocation.is<JoinRemote>()) {
auto address = (HostAddressWithPort)location.get<JoinRemote>();
- Logger::info("Setting steam rich presence connection as address_%s", address);
- SteamFriends()->SetRichPresence("connect", strf("+platform:connect:address_%s", address).c_str());
+ Logger::info("Setting steam rich presence connection as address_{}", address);
+ SteamFriends()->SetRichPresence("connect", strf("+platform:connect:address_{}", address).c_str());
}
}
#endif
@@ -562,9 +562,9 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) {
#ifdef STAR_ENABLE_DISCORD_INTEGRATION
if (m_state->discordAvailable && m_state->discordCurrentUser) {
if (m_discordServerLobby) {
- Logger::info("Deleting discord server lobby %s", m_discordServerLobby->first);
+ Logger::info("Deleting discord server lobby {}", m_discordServerLobby->first);
m_state->discordCore->LobbyManager().DeleteLobby(m_discordServerLobby->first, [](discord::Result res) {
- Logger::error("Could not connect delete server lobby (err %s)", (int)res);
+ Logger::error("Could not connect delete server lobby (err {})", (int)res);
});
}
@@ -591,21 +591,21 @@ void PcP2PNetworkingService::setJoinLocation(JoinLocation location) {
// successfully joined lobby network
return;
} else {
- Logger::error("Failed to open discord main network channel (err %s)", (int)res);
+ Logger::error("Failed to open discord main network channel (err {})", (int)res);
}
} else {
- Logger::error("Failed to join discord lobby network (err %s)", (int)res);
+ Logger::error("Failed to join discord lobby network (err {})", (int)res);
}
// Created lobby but failed to join the lobby network, delete lobby
- Logger::error("Failed to join discord lobby network (err %s)", (int)res);
+ Logger::error("Failed to join discord lobby network (err {})", (int)res);
- Logger::info("Deleting discord lobby %s", lobbyId);
+ Logger::info("Deleting discord lobby {}", lobbyId);
m_state->discordCore->LobbyManager().DeleteLobby(lobbyId, [lobbyId](discord::Result res) {
- Logger::error("failed to delete lobby %s (err %s)", lobbyId, (int)res);
+ Logger::error("failed to delete lobby {} (err {})", lobbyId, (int)res);
});
} else {
- Logger::error("failed to create discord lobby (err %s)", (int)res);
+ Logger::error("failed to create discord lobby (err {})", (int)res);
}
});
}
diff --git a/source/application/StarPlatformServices_pc.cpp b/source/application/StarPlatformServices_pc.cpp
index 7e528f0..7023129 100644
--- a/source/application/StarPlatformServices_pc.cpp
+++ b/source/application/StarPlatformServices_pc.cpp
@@ -43,26 +43,26 @@ PcPlatformServicesState::PcPlatformServicesState()
discord::User user;
auto res = discordCore->UserManager().GetCurrentUser(&user);
if (res != discord::Result::Ok)
- Logger::error("Could not get current discord user. (err %s)", (int)res);
+ Logger::error("Could not get current discord user. (err {})", (int)res);
else
discordCurrentUser = user;
});
} else {
- Logger::error("Failed to instantiate discord core (err %s)", (int)res);
+ Logger::error("Failed to instantiate discord core (err {})", (int)res);
}
if (discordAvailable) {
MutexLocker locker(discordMutex);
discordCore->SetLogHook(discord::LogLevel::Info, [](discord::LogLevel level, char const* msg) {
if (level == discord::LogLevel::Debug)
- Logger::debug("[DISCORD]: %s", msg);
+ Logger::debug("[DISCORD]: {}", msg);
else if (level == discord::LogLevel::Error)
- Logger::debug("[DISCORD]: %s", msg);
+ Logger::debug("[DISCORD]: {}", msg);
else if (level == discord::LogLevel::Info)
- Logger::info("[DISCORD]: %s", msg);
+ Logger::info("[DISCORD]: {}", msg);
else if (level == discord::LogLevel::Warn)
- Logger::warn("[DISCORD]: %s", msg);
+ Logger::warn("[DISCORD]: {}", msg);
});
discordEventShutdown = false;
discordEventThread = Thread::invoke("PcPlatformServices::discordEventThread", [this]() {
@@ -117,10 +117,10 @@ PcPlatformServicesUPtr PcPlatformServices::create(String const& path, StringList
auto p2pNetworkingService = make_shared<PcP2PNetworkingService>(services->m_state);
for (auto& argument : platformArguments) {
if (argument.beginsWith("+platform:connect:")) {
- Logger::info("PC platform services joining from command line argument '%s'", argument);
+ Logger::info("PC platform services joining from command line argument '{}'", argument);
p2pNetworkingService->addPendingJoin(move(argument));
} else {
- throw ApplicationException::format("Unrecognized PC platform services command line argument '%s'", argument);
+ throw ApplicationException::format("Unrecognized PC platform services command line argument '{}'", argument);
}
}
@@ -138,7 +138,7 @@ PcPlatformServicesUPtr PcPlatformServices::create(String const& path, StringList
#ifdef STAR_ENABLE_DISCORD_INTEGRATION
MutexLocker discordLocker(services->m_state->discordMutex);
if (services->m_state->discordAvailable) {
- Logger::debug("Registering starbound to discord at path: %s", path);
+ Logger::debug("Registering starbound to discord at path: {}", path);
services->m_state->discordCore->ActivityManager().RegisterCommand(path.utf8Ptr());
}
#endif
diff --git a/source/application/StarRenderer_opengl20.cpp b/source/application/StarRenderer_opengl20.cpp
index e80d745..82d4845 100644
--- a/source/application/StarRenderer_opengl20.cpp
+++ b/source/application/StarRenderer_opengl20.cpp
@@ -76,7 +76,7 @@ OpenGl20Renderer::OpenGl20Renderer() {
if (!GLEW_VERSION_2_0)
throw RendererException("OpenGL 2.0 not available!");
- Logger::info("OpenGL version: '%s' vendor: '%s' renderer: '%s' shader: '%s'",
+ Logger::info("OpenGL version: '{}' vendor: '{}' renderer: '{}' shader: '{}'",
(const char*)glGetString(GL_VERSION),
(const char*)glGetString(GL_VENDOR),
(const char*)glGetString(GL_RENDERER),
@@ -132,7 +132,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
glGetShaderInfoLog(shader, sizeof(logBuffer), NULL, logBuffer);
- throw RendererException(strf("Failed to compile %s shader: %s\n", name, logBuffer));
+ throw RendererException(strf("Failed to compile {} shader: {}\n", name, logBuffer));
}
return shader;
@@ -158,7 +158,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
if (!status) {
glGetProgramInfoLog(program, sizeof(logBuffer), NULL, logBuffer);
glDeleteProgram(program);
- throw RendererException(strf("Failed to link program: %s\n", logBuffer));
+ throw RendererException(strf("Failed to link program: {}\n", logBuffer));
}
if (m_program != 0)
@@ -175,8 +175,8 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
m_textureUniforms.clear();
m_textureSizeUniforms.clear();
for (size_t i = 0; i < MultiTextureCount; ++i) {
- m_textureUniforms.append(glGetUniformLocation(m_program, strf("texture%s", i).c_str()));
- m_textureSizeUniforms.append(glGetUniformLocation(m_program, strf("textureSize%s", i).c_str()));
+ m_textureUniforms.append(glGetUniformLocation(m_program, strf("texture{}", i).c_str()));
+ m_textureSizeUniforms.append(glGetUniformLocation(m_program, strf("textureSize{}", i).c_str()));
}
m_screenSizeUniform = glGetUniformLocation(m_program, "screenSize");
m_vertexTransformUniform = glGetUniformLocation(m_program, "vertexTransform");
@@ -193,7 +193,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
effectParameter.parameterUniform = glGetUniformLocation(m_program, p.second.getString("uniform").utf8Ptr());
if (effectParameter.parameterUniform == -1) {
- Logger::warn("OpenGL20 effect parameter '%s' has no associated uniform, skipping", p.first);
+ Logger::warn("OpenGL20 effect parameter '{}' has no associated uniform, skipping", p.first);
} else {
String type = p.second.getString("type");
if (type == "bool") {
@@ -209,7 +209,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
} else if (type == "vec4") {
effectParameter.parameterType = RenderEffectParameter::typeIndexOf<Vec4F>();
} else {
- throw RendererException::format("Unrecognized effect parameter type '%s'", type);
+ throw RendererException::format("Unrecognized effect parameter type '{}'", type);
}
m_effectParameters[p.first] = effectParameter;
@@ -243,7 +243,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
EffectTexture effectTexture;
effectTexture.textureUniform = glGetUniformLocation(m_program, p.second.getString("textureUniform").utf8Ptr());
if (effectTexture.textureUniform == -1) {
- Logger::warn("OpenGL20 effect parameter '%s' has no associated uniform, skipping", p.first);
+ Logger::warn("OpenGL20 effect parameter '{}' has no associated uniform, skipping", p.first);
} else {
effectTexture.textureUnit = parameterTextureUnit++;
glUniform1i(effectTexture.textureUniform, effectTexture.textureUnit);
@@ -253,7 +253,7 @@ void OpenGl20Renderer::setEffectConfig(Json const& effectConfig, StringMap<Strin
if (auto tsu = p.second.optString("textureSizeUniform")) {
effectTexture.textureSizeUniform = glGetUniformLocation(m_program, tsu->utf8Ptr());
if (effectTexture.textureSizeUniform == -1)
- Logger::warn("OpenGL20 effect parameter '%s' has textureSizeUniform '%s' with no associated uniform", p.first, *tsu);
+ Logger::warn("OpenGL20 effect parameter '{}' has textureSizeUniform '{}' with no associated uniform", p.first, *tsu);
}
m_effectTextures[p.first] = effectTexture;
@@ -270,7 +270,7 @@ void OpenGl20Renderer::setEffectParameter(String const& parameterName, RenderEff
return;
if (ptr->parameterType != value.typeIndex())
- throw RendererException::format("OpenGL20Renderer::setEffectParameter '%s' parameter type mismatch", parameterName);
+ throw RendererException::format("OpenGL20Renderer::setEffectParameter '{}' parameter type mismatch", parameterName);
flushImmediatePrimitives();
@@ -354,7 +354,7 @@ TextureGroupPtr OpenGl20Renderer::createTextureGroup(TextureGroupSize textureSiz
else // TextureGroupSize::Small
atlasNumCells = 64;
- Logger::info("detected supported OpenGL texture size %s, using atlasNumCells %s", maxTextureSize, atlasNumCells);
+ Logger::info("detected supported OpenGL texture size {}, using atlasNumCells {}", maxTextureSize, atlasNumCells);
auto glTextureGroup = make_shared<GlTextureGroup>(atlasNumCells);
glTextureGroup->textureAtlasSet.textureFiltering = filtering;
diff --git a/source/application/StarStatisticsService_pc_steam.cpp b/source/application/StarStatisticsService_pc_steam.cpp
index 89239fd..bf74b7f 100644
--- a/source/application/StarStatisticsService_pc_steam.cpp
+++ b/source/application/StarStatisticsService_pc_steam.cpp
@@ -52,7 +52,7 @@ bool SteamStatisticsService::reportEvent(String const&, Json const&) {
bool SteamStatisticsService::unlockAchievement(String const& name) {
if (!SteamUserStats()->SetAchievement(name.utf8Ptr())) {
- Logger::error("Cannot set Steam achievement %s", name);
+ Logger::error("Cannot set Steam achievement {}", name);
return false;
}
return true;
@@ -94,7 +94,7 @@ void SteamStatisticsService::onUserStatsReceived(UserStatsReceived_t* callback)
return;
if (callback->m_eResult != k_EResultOK) {
- m_error = {strf("Steam RequestCurrentStats failed with code %d", (int)callback->m_eResult)};
+ m_error = {strf("Steam RequestCurrentStats failed with code {}", (int)callback->m_eResult)};
return;
}
@@ -117,14 +117,14 @@ void SteamStatisticsService::onUserStatsStored(UserStatsStored_t* callback) {
return;
}
- m_error = {strf("Steam StoreStats failed with code %d", (int)callback->m_eResult)};
+ m_error = {strf("Steam StoreStats failed with code {}", (int)callback->m_eResult)};
}
void SteamStatisticsService::onAchievementStored(UserAchievementStored_t* callback) {
if (callback->m_nGameID != m_appId)
return;
- Logger::debug("Steam achievement %s stored successfully", callback->m_rgchAchievementName);
+ Logger::debug("Steam achievement {} stored successfully", callback->m_rgchAchievementName);
}
}
diff --git a/source/base/StarAnimatedPartSet.cpp b/source/base/StarAnimatedPartSet.cpp
index 62bf786..3f5d72a 100644
--- a/source/base/StarAnimatedPartSet.cpp
+++ b/source/base/StarAnimatedPartSet.cpp
@@ -231,7 +231,7 @@ AnimatedPartSet::AnimationMode AnimatedPartSet::stringToAnimationMode(String con
} else if (string.equals("transition", String::CaseInsensitive)) {
return Transition;
} else {
- throw AnimatedPartSetException(strf("No such AnimationMode '%s'", string));
+ throw AnimatedPartSetException(strf("No such AnimationMode '{}'", string));
}
}
diff --git a/source/base/StarAssets.cpp b/source/base/StarAssets.cpp
index a24000d..ce80136 100644
--- a/source/base/StarAssets.cpp
+++ b/source/base/StarAssets.cpp
@@ -22,7 +22,7 @@ namespace Star {
static void validatePath(AssetPath const& components, bool canContainSubPath, bool canContainDirectives) {
if (components.basePath.empty() || components.basePath[0] != '/')
- throw AssetException(strf("Path '%s' must be absolute", components.basePath));
+ throw AssetException(strf("Path '{}' must be absolute", components.basePath));
bool first = true;
bool slashed = true;
@@ -31,19 +31,19 @@ static void validatePath(AssetPath const& components, bool canContainSubPath, bo
if (c == '/') {
if (!first) {
if (slashed)
- throw AssetException(strf("Path '%s' contains consecutive //, not allowed", components.basePath));
+ throw AssetException(strf("Path '{}' contains consecutive //, not allowed", components.basePath));
else if (dotted)
- throw AssetException(strf("Path '%s' '.' and '..' not allowed", components.basePath));
+ throw AssetException(strf("Path '{}' '.' and '..' not allowed", components.basePath));
}
slashed = true;
dotted = false;
} else if (c == ':') {
if (slashed)
- throw AssetException(strf("Path '%s' has ':' after directory", components.basePath));
+ throw AssetException(strf("Path '{}' has ':' after directory", components.basePath));
break;
} else if (c == '?') {
if (slashed)
- throw AssetException(strf("Path '%s' has '?' after directory", components.basePath));
+ throw AssetException(strf("Path '{}' has '?' after directory", components.basePath));
break;
} else {
slashed = false;
@@ -52,12 +52,12 @@ static void validatePath(AssetPath const& components, bool canContainSubPath, bo
first = false;
}
if (slashed)
- throw AssetException(strf("Path '%s' cannot be a file", components.basePath));
+ throw AssetException(strf("Path '{}' cannot be a file", components.basePath));
if (!canContainSubPath && components.subPath)
- throw AssetException::format("Path '%s' cannot contain sub-path", components);
+ throw AssetException::format("Path '{}' cannot contain sub-path", components);
if (!canContainDirectives && !components.directives.empty())
- throw AssetException::format("Path '%s' cannot contain directives", components);
+ throw AssetException::format("Path '{}' cannot contain directives", components);
}
Maybe<RectU> FramesSpecification::getRect(String const& frame) const {
@@ -76,7 +76,7 @@ Assets::Assets(Settings settings, StringList assetSources) {
m_assetSources = move(assetSources);
for (auto& sourcePath : m_assetSources) {
- Logger::info("Loading assets from: '%s'", sourcePath);
+ Logger::info("Loading assets from: '{}'", sourcePath);
AssetSourcePtr source;
if (File::isDirectory(sourcePath))
source = make_shared<DirectoryAssetSource>(sourcePath, m_settings.pathIgnore);
@@ -168,7 +168,7 @@ String Assets::assetSource(String const& path) const {
MutexLocker assetsLocker(m_assetsMutex);
if (auto p = m_files.ptr(path))
return m_assetSourcePaths.getLeft(p->source);
- throw AssetException(strf("No such asset '%s'", path));
+ throw AssetException(strf("No such asset '{}'", path));
}
StringList Assets::scan(String const& suffix) const {
@@ -384,7 +384,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
RectU rect = RectU(jsonToRectI(pair.second));
if (rect.isEmpty())
throw AssetException(
- strf("Empty rect in frame specification in image %s frame %s", framesSpecification.framesFile, frameName));
+ strf("Empty rect in frame specification in image {} frame {}", framesSpecification.framesFile, frameName));
else
framesSpecification.frames[frameName] = rect;
}
@@ -398,13 +398,13 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
Vec2U dimensions(jsonToVec2I(grid.get("dimensions")));
if (dimensions[0] == 0 || dimensions[1] == 0)
- throw AssetException(strf("Image %s \"dimensions\" in frameGrid cannot be zero", framesSpecification.framesFile));
+ throw AssetException(strf("Image {} \"dimensions\" in frameGrid cannot be zero", framesSpecification.framesFile));
if (grid.contains("names")) {
auto nameList = grid.get("names");
for (size_t y = 0; y < nameList.size(); ++y) {
if (y >= dimensions[1])
- throw AssetException(strf("Image %s row %s is out of bounds for y-dimension %s",
+ throw AssetException(strf("Image {} row {} is out of bounds for y-dimension {}",
framesSpecification.framesFile,
y + 1,
dimensions[1]));
@@ -413,7 +413,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
continue;
for (unsigned x = 0; x < rowList.size(); ++x) {
if (x >= dimensions[0])
- throw AssetException(strf("Image %s column %s is out of bounds for x-dimension %s",
+ throw AssetException(strf("Image {} column {} is out of bounds for x-dimension {}",
framesSpecification.framesFile,
x + 1,
dimensions[0]));
@@ -431,7 +431,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
// If "names" not specified, use auto naming algorithm
for (size_t y = 0; y < dimensions[1]; ++y)
for (size_t x = 0; x < dimensions[0]; ++x)
- framesSpecification.frames[strf("%s", y * dimensions[0] + x)] =
+ framesSpecification.frames[strf("{}", y * dimensions[0] + x)] =
RectU::withSize(Vec2U(begin[0] + x * size[0], begin[1] + y * size[1]), size);
}
}
@@ -449,7 +449,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
auto it = aliases->find(value);
if (it != aliases->end()) {
if (i == aliases->size())
- throw AssetException(strf("Infinite alias loop detected for alias '%s'", key));
+ throw AssetException(strf("Infinite alias loop detected for alias '{}'", key));
value = it->second.toString();
} else {
@@ -458,7 +458,7 @@ FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, St
}
if (!framesSpecification.frames.contains(value))
- throw AssetException(strf("No such frame '%s' found for alias '%s'", value, key));
+ throw AssetException(strf("No such frame '{}' found for alias '{}'", value, key));
framesSpecification.aliases[key] = move(value);
}
}
@@ -493,7 +493,7 @@ shared_ptr<Assets::AssetData> Assets::tryAsset(AssetId const& id) const {
freshen(i->second);
return i->second;
} else {
- throw AssetException::format("Error loading asset %s", id.path);
+ throw AssetException::format("Error loading asset {}", id.path);
}
} else {
auto j = m_queue.find(id);
@@ -516,7 +516,7 @@ shared_ptr<Assets::AssetData> Assets::getAsset(AssetId const& id) const {
freshen(asset);
return asset;
} else {
- throw AssetException::format("Error loading asset %s", id.path);
+ throw AssetException::format("Error loading asset {}", id.path);
}
} else {
// Try to load the asset in-thread, if we cannot, then the asset has been
@@ -648,13 +648,13 @@ FramesSpecificationConstPtr Assets::bestFramesSpecification(String const& image)
IODevicePtr Assets::open(String const& path) const {
if (auto p = m_files.ptr(path))
return p->source->open(p->sourceName);
- throw AssetException(strf("No such asset '%s'", path));
+ throw AssetException(strf("No such asset '{}'", path));
}
ByteArray Assets::read(String const& path) const {
if (auto p = m_files.ptr(path))
return p->source->read(p->sourceName);
- throw AssetException(strf("No such asset '%s'", path));
+ throw AssetException(strf("No such asset '{}'", path));
}
Json Assets::readJson(String const& path) const {
@@ -673,21 +673,21 @@ Json Assets::readJson(String const& path) const {
try {
result = jsonPatch(result, patch.toArray());
} catch (JsonPatchTestFail const& e) {
- Logger::debug("Patch test failure from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
+ Logger::debug("Patch test failure from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
}
}
} else if (patchData.at(0).type() == Json::Type::Object) {
try {
result = jsonPatch(result, patchData);
} catch (JsonPatchTestFail const& e) {
- Logger::debug("Patch test failure from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
+ Logger::debug("Patch test failure from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
}
} else {
- throw JsonPatchException(strf("Patch data is wrong type: %s", Json::typeName(patchData.at(0).type())));
+ throw JsonPatchException(strf("Patch data is wrong type: {}", Json::typeName(patchData.at(0).type())));
}
}
} catch (JsonPatchException const& e) {
- Logger::error("Could not apply patch from file %s in source: %s. Caused by: %s", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
+ Logger::error("Could not apply patch from file {} in source: {}. Caused by: {}", pair.first, m_assetSourcePaths.getLeft(pair.second), e.what());
}
}
else if (patchJson.isType(Json::Type::Object)) { //Kae: Do a good ol' json merge instead if the .patch file is a Json object
@@ -697,7 +697,7 @@ Json Assets::readJson(String const& path) const {
}
return result;
} catch (std::exception const& e) {
- throw JsonParsingException(strf("Cannot parse json file: %s", path), e);
+ throw JsonParsingException(strf("Cannot parse json file: {}", path), e);
}
}
@@ -707,9 +707,9 @@ bool Assets::doLoad(AssetId const& id) const {
// data.
return (bool)loadAsset(id);
} catch (std::exception const& e) {
- Logger::error("Exception caught loading asset: %s, %s", id.path, outputException(e, true));
+ Logger::error("Exception caught loading asset: {}, {}", id.path, outputException(e, true));
} catch (...) {
- Logger::error("Unknown exception caught loading asset: %s", id.path);
+ Logger::error("Unknown exception caught loading asset: {}", id.path);
}
// There was an exception, remove the asset from the queue and fill the cache
@@ -727,9 +727,9 @@ bool Assets::doPost(AssetId const& id) const {
if (id.type == AssetType::Audio)
assetData = postProcessAudio(assetData);
} catch (std::exception const& e) {
- Logger::error("Exception caught post-processing asset: %s, %s", id.path, outputException(e, true));
+ Logger::error("Exception caught post-processing asset: {}, {}", id.path, outputException(e, true));
} catch (...) {
- Logger::error("Unknown exception caught post-processing asset: %s", id.path);
+ Logger::error("Unknown exception caught post-processing asset: {}", id.path);
}
m_queue.remove(id);
@@ -769,10 +769,10 @@ shared_ptr<Assets::AssetData> Assets::loadAsset(AssetId const& id) const {
} catch (StarException const& e) {
if (id.type == AssetType::Image && m_settings.missingImage) {
- Logger::error("Could not load image asset '%s', using placeholder default.\n%s", id.path, outputException(e, false));
+ Logger::error("Could not load image asset '{}', using placeholder default.\n{}", id.path, outputException(e, false));
assetData = loadImage({*m_settings.missingImage, {}, {}});
} else if (id.type == AssetType::Audio && m_settings.missingAudio) {
- Logger::error("Could not load audio asset '%s', using placeholder default.\n%s", id.path, outputException(e, false));
+ Logger::error("Could not load audio asset '{}', using placeholder default.\n{}", id.path, outputException(e, false));
assetData = loadAudio({*m_settings.missingAudio, {}, {}});
} else {
throw;
@@ -821,7 +821,7 @@ shared_ptr<Assets::AssetData> Assets::loadJson(AssetPath const& path) const {
newData->json = topJson->json.query(*path.subPath);
return newData;
} catch (StarException const& e) {
- throw AssetException(strf("Could not read JSON value %s", path), e);
+ throw AssetException(strf("Could not read JSON value {}", path), e);
}
} else {
return unlockDuring([&]() {
@@ -830,7 +830,7 @@ shared_ptr<Assets::AssetData> Assets::loadJson(AssetPath const& path) const {
newData->json = readJson(path.basePath);
return newData;
} catch (StarException const& e) {
- throw AssetException(strf("Could not read JSON asset %s", path), e);
+ throw AssetException(strf("Could not read JSON asset {}", path), e);
}
});
}
@@ -882,7 +882,7 @@ shared_ptr<Assets::AssetData> Assets::loadImage(AssetPath const& path) const {
// Base image must have frames data associated with it.
if (!imageData->frames)
- throw AssetException::format("No associated frames file found for image '%s' while resolving image frame '%s'", path.basePath, path);
+ throw AssetException::format("No associated frames file found for image '{}' while resolving image frame '{}'", path.basePath, path);
if (auto alias = imageData->frames->aliases.ptr(*path.subPath)) {
imageData = as<ImageData>(loadAsset(AssetId{AssetType::Image, {path.basePath, *alias, path.directives}}));
@@ -897,7 +897,7 @@ shared_ptr<Assets::AssetData> Assets::loadImage(AssetPath const& path) const {
} else {
auto frameRect = imageData->frames->frames.ptr(*path.subPath);
if (!frameRect)
- throw AssetException(strf("No such frame %s in frames spec %s", *path.subPath, imageData->frames->framesFile));
+ throw AssetException(strf("No such frame {} in frames spec {}", *path.subPath, imageData->frames->framesFile));
return unlockDuring([&]() {
// Need to flip frame coordinates because frame configs assume top
diff --git a/source/base/StarDirectoryAssetSource.cpp b/source/base/StarDirectoryAssetSource.cpp
index bd8c760..675c64c 100644
--- a/source/base/StarDirectoryAssetSource.cpp
+++ b/source/base/StarDirectoryAssetSource.cpp
@@ -17,7 +17,7 @@ DirectoryAssetSource::DirectoryAssetSource(String const& baseDirectory, StringLi
m_metadata = Json::parseJson(File::readFileString(metadataFile)).toObject();
break;
} catch (JsonException const& e) {
- throw AssetSourceException(strf("Could not load metadata file '%s' from assets", metadataFile), e);
+ throw AssetSourceException(strf("Could not load metadata file '{}' from assets", metadataFile), e);
}
}
}
@@ -52,7 +52,7 @@ ByteArray DirectoryAssetSource::read(String const& path) {
String DirectoryAssetSource::toFilesystem(String const& path) const {
if (!path.beginsWith("/"))
- throw AssetSourceException::format("Asset path '%s' must be absolute in DirectoryAssetSource::toFilesystem", path);
+ throw AssetSourceException::format("Asset path '{}' must be absolute in DirectoryAssetSource::toFilesystem", path);
else
return File::relativeTo(m_baseDirectory, File::convertDirSeparators(path.substr(1)));
}
diff --git a/source/base/StarPackedAssetSource.cpp b/source/base/StarPackedAssetSource.cpp
index fe16a80..b335c2f 100644
--- a/source/base/StarPackedAssetSource.cpp
+++ b/source/base/StarPackedAssetSource.cpp
@@ -140,7 +140,7 @@ IODevicePtr PackedAssetSource::open(String const& path) {
auto p = m_index.ptr(path);
if (!p)
- throw AssetSourceException::format("Requested file '%s' does not exist in the packed assets file", path);
+ throw AssetSourceException::format("Requested file '{}' does not exist in the packed assets file", path);
return make_shared<AssetReader>(m_packedFile, p->first, p->second);
}
@@ -148,7 +148,7 @@ IODevicePtr PackedAssetSource::open(String const& path) {
ByteArray PackedAssetSource::read(String const& path) {
auto p = m_index.ptr(path);
if (!p)
- throw AssetSourceException::format("Requested file '%s' does not exist in the packed assets file", path);
+ throw AssetSourceException::format("Requested file '{}' does not exist in the packed assets file", path);
ByteArray data(p->second, 0);
m_packedFile->readFullAbsolute(p->first, data.ptr(), p->second);
diff --git a/source/base/StarVersionOptionParser.cpp b/source/base/StarVersionOptionParser.cpp
index 85995ec..f972975 100644
--- a/source/base/StarVersionOptionParser.cpp
+++ b/source/base/StarVersionOptionParser.cpp
@@ -4,8 +4,8 @@
namespace Star {
void VersionOptionParser::printVersion(std::ostream& os) {
- format(os, "Starbound Version %s (%s)\n", StarVersionString, StarArchitectureString);
- format(os, "Source Identifier - %s\n", StarSourceIdentifierString);
+ format(os, "Starbound Version {} ({})\n", StarVersionString, StarArchitectureString);
+ format(os, "Source Identifier - {}\n", StarSourceIdentifierString);
}
VersionOptionParser::VersionOptionParser() {
@@ -29,7 +29,7 @@ VersionOptionParser::Options VersionOptionParser::parseOrDie(StringList const& c
if (!errors.empty()) {
for (auto const& err : errors)
- coutf("Error: %s\n", err);
+ coutf("Error: {}\n", err);
coutf("\n");
printHelp(std::cout);
std::exit(1);
diff --git a/source/client/StarClientApplication.cpp b/source/client/StarClientApplication.cpp
index 907f357..a4e190f 100644
--- a/source/client/StarClientApplication.cpp
+++ b/source/client/StarClientApplication.cpp
@@ -127,7 +127,7 @@ void ClientApplication::startup(StringList const& cmdLineArgs) {
RootLoader rootLoader({AdditionalAssetsSettings, AdditionalDefaultConfiguration, String("starbound.log"), LogLevel::Info, false, String("starbound.config")});
m_root = rootLoader.initOrDie(cmdLineArgs).first;
- Logger::info("Client Version %s (%s) Source ID: %s Protocol: %s", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion);
+ Logger::info("Client Version {} ({}) Source ID: {} Protocol: {}", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion);
}
void ClientApplication::shutdown() {
@@ -198,7 +198,7 @@ void ClientApplication::renderInit(RendererPtr renderer) {
Application::renderInit(renderer);
auto assets = m_root->assets();
- String rendererConfig = strf("/rendering/%s.config", renderer->rendererId());
+ String rendererConfig = strf("/rendering/{}.config", renderer->rendererId());
if (assets->assetExists(rendererConfig)) {
StringMap<String> shaders;
auto config = assets->json(rendererConfig);
@@ -216,7 +216,7 @@ void ClientApplication::renderInit(RendererPtr renderer) {
renderer->setEffectConfig(config, shaders);
}
else
- Logger::warn("No rendering config found for renderer with id '%s'", renderer->rendererId());
+ Logger::warn("No rendering config found for renderer with id '{}'", renderer->rendererId());
if (m_root->configuration()->get("limitTextureAtlasSize").optBool().value(false))
renderer->setSizeLimitEnabled(true);
@@ -489,7 +489,7 @@ void ClientApplication::changeState(MainAppState newState) {
try {
packetSocket = TcpPacketSocket::open(TcpSocket::connectTo(*address));
} catch (StarException const& e) {
- setError(strf("Join failed! Error connecting to '%s'", *address), e);
+ setError(strf("Join failed! Error connecting to '{}'", *address), e);
return;
}
@@ -499,7 +499,7 @@ void ClientApplication::changeState(MainAppState newState) {
if (auto p2pNetworkingService = appController()->p2pNetworkingService()) {
auto result = p2pNetworkingService->connectToPeer(*p2pPeerId);
if (result.isLeft()) {
- setError(strf("Cannot join peer: %s", result.left()));
+ setError(strf("Cannot join peer: {}", result.left()));
return;
} else {
packetSocket = P2PPacketSocket::open(move(result.right()));
@@ -534,7 +534,7 @@ void ClientApplication::changeState(MainAppState newState) {
}
if (auto errorMessage = m_universeClient->connect(m_universeServer->addLocalClient(), "", "")) {
- setError(strf("Error connecting locally: %s", *errorMessage));
+ setError(strf("Error connecting locally: {}", *errorMessage));
return;
}
}
@@ -558,8 +558,8 @@ void ClientApplication::setError(String const& error) {
}
void ClientApplication::setError(String const& error, std::exception const& e) {
- Logger::error("%s\n%s", error, outputException(e, true));
- m_errorScreen->setMessage(strf("%s\n%s", error, outputException(e, false)));
+ Logger::error("{}\n{}", error, outputException(e, true));
+ m_errorScreen->setMessage(strf("{}\n{}", error, outputException(e, false)));
}
void ClientApplication::updateMods() {
@@ -570,10 +570,10 @@ void ClientApplication::updateMods() {
StringList modDirectories;
for (auto contentId : ugcService->subscribedContentIds()) {
if (auto contentDirectory = ugcService->contentDownloadDirectory(contentId)) {
- Logger::info("Loading mods from user generated content with id '%s' from directory '%s'", contentId, *contentDirectory);
+ Logger::info("Loading mods from user generated content with id '{}' from directory '{}'", contentId, *contentDirectory);
modDirectories.append(*contentDirectory);
} else {
- Logger::warn("User generated content with id '%s' is not available", contentId);
+ Logger::warn("User generated content with id '{}' is not available", contentId);
}
}
@@ -656,7 +656,7 @@ void ClientApplication::updateTitle() {
changeState(MainAppState::MultiPlayer);
}
} else {
- setError(strf("invalid port: %s", portString));
+ setError(strf("invalid port: {}", portString));
}
} else {
changeState(MainAppState::MultiPlayer);
@@ -760,7 +760,7 @@ void ClientApplication::updateRunning() {
m_cinematicOverlay->stop();
String errMessage;
if (auto disconnectReason = m_universeClient->disconnectReason())
- errMessage = strf("You were disconnected from the server for the following reason:\n%s", *disconnectReason);
+ errMessage = strf("You were disconnected from the server for the following reason:\n{}", *disconnectReason);
else
errMessage = "Client-server connection no longer valid!";
setError(errMessage);
@@ -805,12 +805,12 @@ void ClientApplication::updateRunning() {
Vec2F aimPosition = m_player->aimPosition();
LogMap::set("render_fps", appController()->renderFps());
LogMap::set("update_rate", appController()->updateRate());
- LogMap::set("player_pos", strf("%4.2f %4.2f", m_player->position()[0], m_player->position()[1]));
- LogMap::set("player_vel", strf("%4.2f %4.2f", m_player->velocity()[0], m_player->velocity()[1]));
- LogMap::set("player_aim", strf("%4.2f %4.2f", aimPosition[0], aimPosition[1]));
+ LogMap::set("player_pos", strf("{:4.2f} {:4.2f}", m_player->position()[0], m_player->position()[1]));
+ LogMap::set("player_vel", strf("{:4.2f} {:4.2f}", m_player->velocity()[0], m_player->velocity()[1]));
+ LogMap::set("player_aim", strf("{:4.2f} {:4.2f}", aimPosition[0], aimPosition[1]));
if (m_universeClient->worldClient()) {
- LogMap::set("liquid_level", strf("%d", m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level));
- LogMap::set("dungeonId", strf("%d", m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition))));
+ LogMap::set("liquid_level", strf("{}", m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level));
+ LogMap::set("dungeonId", strf("{}", m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition))));
}
if (m_mainInterface->currentState() == MainInterface::ReturnToTitle)
diff --git a/source/core/StarAudio.cpp b/source/core/StarAudio.cpp
index 7e4cd31..ef5d2f4 100644
--- a/source/core/StarAudio.cpp
+++ b/source/core/StarAudio.cpp
@@ -59,13 +59,13 @@ namespace {
uint32_t fileSize = readLEType<uint32_t>(device);
fileSize += sigLength + sizeof(fileSize);
if (fileSize != device->size())
- throw AudioException(strf("Wav file is wrong size, reports %d is actually %d", fileSize, device->size()));
+ throw AudioException(strf("Wav file is wrong size, reports {} is actually {}", fileSize, device->size()));
device->readFull(waveSig.get(), sigLength);
if ((strcmp(riffSig.get(), "RIFF") != 0) || (strcmp(waveSig.get(), "WAVE") != 0)) { // bytes are not magic
auto p = [](char a) { return isprint(a) ? a : '?'; };
- throw AudioException(strf("Wav file has wrong magic bytes, got `%c%c%c%c' and `%c%c%c%c' but expected `RIFF' and `WAVE'",
+ throw AudioException(strf("Wav file has wrong magic bytes, got `{}{}{}{}' and `{}{}{}{}' but expected `RIFF' and `WAVE'",
p(riffSig[0]), p(riffSig[1]), p(riffSig[2]), p(riffSig[3]), p(waveSig[0]), p(waveSig[1]), p(waveSig[2]), p(waveSig[3])));
}
@@ -74,7 +74,7 @@ namespace {
device->readFull(fmtSig.get(), sigLength);
if (strcmp(fmtSig.get(), "fmt ") != 0) { // friendship is magic
auto p = [](char a) { return isprint(a) ? a : '?'; };
- throw AudioException(strf("Wav file fmt subchunk has wrong magic bytes, got `%c%c%c%c' but expected `fmt '",
+ throw AudioException(strf("Wav file fmt subchunk has wrong magic bytes, got `{}{}{}{}' but expected `fmt '",
p(fmtSig[0]),
p(fmtSig[1]),
p(fmtSig[2]),
@@ -84,7 +84,7 @@ namespace {
uint32_t fmtSubchunkSize = readLEType<uint32_t>(device);
fmtSubchunkSize += sigLength;
if (fmtSubchunkSize < 20)
- throw AudioException(strf("fmt subchunk is sized wrong, expected 20 got %d. Is this wav file not PCM?", fmtSubchunkSize));
+ throw AudioException(strf("fmt subchunk is sized wrong, expected 20 got {}. Is this wav file not PCM?", fmtSubchunkSize));
uint16_t audioFormat = readLEType<uint16_t>(device);
if (audioFormat != 1)
@@ -110,14 +110,14 @@ namespace {
device->readFull(dataSig.get(), sigLength);
if (strcmp(dataSig.get(), "data") != 0) { // magic or more magic?
auto p = [](char a) { return isprint(a) ? a : '?'; };
- throw AudioException(strf("Wav file data subchunk has wrong magic bytes, got `%c%c%c%c' but expected `data'",
+ throw AudioException(strf("Wav file data subchunk has wrong magic bytes, got `{}{}{}{}' but expected `data'",
p(dataSig[0]), p(dataSig[1]), p(dataSig[2]), p(dataSig[3])));
}
uint32_t wavDataSize = readLEType<uint32_t>(device);
size_t wavDataOffset = (size_t)device->pos();
if (wavDataSize + wavDataOffset > (size_t)device->size()) {
- throw AudioException(strf("Wav file data size reported is inconsistent with file size, got %d but expected %d",
+ throw AudioException(strf("Wav file data size reported is inconsistent with file size, got {} but expected {}",
device->size(), wavDataSize + wavDataOffset));
}
diff --git a/source/core/StarBTreeDatabase.cpp b/source/core/StarBTreeDatabase.cpp
index 6983df8..4ac321f 100644
--- a/source/core/StarBTreeDatabase.cpp
+++ b/source/core/StarBTreeDatabase.cpp
@@ -886,7 +886,7 @@ void BTreeDatabase::updateBlock(BlockIndex blockIndex, ByteArray const& block) {
void BTreeDatabase::rawReadBlock(BlockIndex blockIndex, size_t blockOffset, char* block, size_t size) const {
if (blockOffset > m_blockSize || size > m_blockSize - blockOffset)
- throw DBException::format("Read past end of block, offset: %s size %s", blockOffset, size);
+ throw DBException::format("Read past end of block, offset: {} size {}", blockOffset, size);
if (size <= 0)
return;
@@ -896,7 +896,7 @@ void BTreeDatabase::rawReadBlock(BlockIndex blockIndex, size_t blockOffset, char
void BTreeDatabase::rawWriteBlock(BlockIndex blockIndex, size_t blockOffset, char const* block, size_t size) const {
if (blockOffset > m_blockSize || size > m_blockSize - blockOffset)
- throw DBException::format("Write past end of block, offset: %s size %s", blockOffset, size);
+ throw DBException::format("Write past end of block, offset: {} size {}", blockOffset, size);
if (size <= 0)
return;
@@ -910,7 +910,7 @@ auto BTreeDatabase::readFreeIndexBlock(BlockIndex blockIndex) -> FreeIndexBlock
ByteArray magic(2, 0);
rawReadBlock(blockIndex, 0, magic.ptr(), 2);
if (magic != ByteArray(FreeIndexMagic, 2))
- throw DBException::format("Internal exception! block %s missing free index block marker!", blockIndex);
+ throw DBException::format("Internal exception! block {} missing free index block marker!", blockIndex);
FreeIndexBlock freeIndexBlock;
DataStreamBuffer buffer(max(sizeof(BlockIndex), (size_t)4));
@@ -1124,20 +1124,20 @@ void BTreeDatabase::doCommit() {
void BTreeDatabase::checkIfOpen(char const* methodName, bool shouldBeOpen) const {
if (shouldBeOpen && !m_open)
- throw DBException::format("BTreeDatabase method '%s' called when not open, must be open.", methodName);
+ throw DBException::format("BTreeDatabase method '{}' called when not open, must be open.", methodName);
else if (!shouldBeOpen && m_open)
- throw DBException::format("BTreeDatabase method '%s' called when open, cannot call when open.", methodName);
+ throw DBException::format("BTreeDatabase method '{}' called when open, cannot call when open.", methodName);
}
void BTreeDatabase::checkBlockIndex(size_t blockIndex) const {
BlockIndex blockCount = (m_deviceSize - HeaderSize) / m_blockSize;
if (blockIndex >= blockCount)
- throw DBException::format("blockIndex: %s out of block range", blockIndex);
+ throw DBException::format("blockIndex: {} out of block range", blockIndex);
}
void BTreeDatabase::checkKeySize(ByteArray const& k) const {
if (k.size() != m_keySize)
- throw DBException::format("Wrong key size %s", k.size());
+ throw DBException::format("Wrong key size {}", k.size());
}
uint32_t BTreeDatabase::maxFreeIndexLength() const {
diff --git a/source/core/StarBiMap.hpp b/source/core/StarBiMap.hpp
index 3953fde..8e3d616 100644
--- a/source/core/StarBiMap.hpp
+++ b/source/core/StarBiMap.hpp
@@ -179,7 +179,7 @@ template <typename LeftT, typename RightT, typename LeftMapT, typename RightMapT
BiMap<LeftT, RightT, LeftMapT, RightMapT>::BiMap(std::initializer_list<value_type> list) {
for (value_type const& v : list) {
if (!insert(v.first, v.second))
- throw MapException::format("Repeat pair in BiMap initializer_list construction: (%s, %s)", outputAny(v.first), outputAny(v.second));
+ throw MapException::format("Repeat pair in BiMap initializer_list construction: ({}, {})", outputAny(v.first), outputAny(v.second));
}
}
@@ -324,10 +324,10 @@ bool BiMap<LeftT, RightT, LeftMapT, RightMapT>::insert(Left const& left, Right c
template <typename LeftT, typename RightT, typename LeftMapT, typename RightMapT>
void BiMap<LeftT, RightT, LeftMapT, RightMapT>::add(Left const& left, Right const& right) {
if (m_leftMap.contains(left))
- throw MapException(strf("BiMap already contains left side value '%s'", outputAny(left)));
+ throw MapException(strf("BiMap already contains left side value '{}'", outputAny(left)));
if (m_rightMap.contains(right))
- throw MapException(strf("BiMap already contains right side value '%s'", outputAny(right)));
+ throw MapException(strf("BiMap already contains right side value '{}'", outputAny(right)));
insert(left, right);
}
diff --git a/source/core/StarBuffer.cpp b/source/core/StarBuffer.cpp
index e99615c..3212e0a 100644
--- a/source/core/StarBuffer.cpp
+++ b/source/core/StarBuffer.cpp
@@ -90,7 +90,7 @@ void Buffer::open(IOMode mode) {
}
String Buffer::deviceName() const {
- return strf("Buffer <%s>", (void*)this);
+ return strf("Buffer <{}>", (void*)this);
}
StreamOffset Buffer::size() {
@@ -244,7 +244,7 @@ size_t ExternalBuffer::writeAbsolute(StreamOffset, char const*, size_t) {
}
String ExternalBuffer::deviceName() const {
- return strf("ExternalBuffer <%s>", (void*)this);
+ return strf("ExternalBuffer <{}>", (void*)this);
}
StreamOffset ExternalBuffer::size() {
diff --git a/source/core/StarByteArray.cpp b/source/core/StarByteArray.cpp
index 944071b..6414c46 100644
--- a/source/core/StarByteArray.cpp
+++ b/source/core/StarByteArray.cpp
@@ -85,14 +85,14 @@ void ByteArray::reserve(size_t newCapacity) {
if (!m_data) {
auto newMem = (char*)Star::malloc(newCapacity);
if (!newMem)
- throw MemoryException::format("Could not set new ByteArray capacity %s\n", newCapacity);
+ throw MemoryException::format("Could not set new ByteArray capacity {}\n", newCapacity);
m_data = newMem;
m_capacity = newCapacity;
} else {
newCapacity = max({m_capacity * 2, newCapacity, (size_t)8});
auto newMem = (char*)Star::realloc(m_data, newCapacity);
if (!newMem)
- throw MemoryException::format("Could not set new ByteArray capacity %s\n", newCapacity);
+ throw MemoryException::format("Could not set new ByteArray capacity {}\n", newCapacity);
m_data = newMem;
m_capacity = newCapacity;
}
diff --git a/source/core/StarByteArray.hpp b/source/core/StarByteArray.hpp
index 9f63643..cb5633b 100644
--- a/source/core/StarByteArray.hpp
+++ b/source/core/StarByteArray.hpp
@@ -242,7 +242,7 @@ inline char ByteArray::operator[](size_t i) const {
inline char ByteArray::at(size_t i) const {
if (i >= m_size)
- throw OutOfRangeException(strf("Out of range in ByteArray::at(%s)", i));
+ throw OutOfRangeException(strf("Out of range in ByteArray::at({})", i));
return m_data[i];
}
diff --git a/source/core/StarCasting.hpp b/source/core/StarCasting.hpp
index 64305af..0c2ed12 100644
--- a/source/core/StarCasting.hpp
+++ b/source/core/StarCasting.hpp
@@ -61,11 +61,11 @@ shared_ptr<Type1 const> as(shared_ptr<Type2 const> const& p) {
template <typename Type, typename Ptr>
auto convert(Ptr const& p) -> decltype(as<Type>(p)) {
if (!p)
- throw PointerConvertException::format("Could not convert from nullptr to %s", typeid(Type).name());
+ throw PointerConvertException::format("Could not convert from nullptr to {}", typeid(Type).name());
else if (auto a = as<Type>(p))
return a;
else
- throw PointerConvertException::format("Could not convert from %s to %s", typeid(*p).name(), typeid(Type).name());
+ throw PointerConvertException::format("Could not convert from {} to {}", typeid(*p).name(), typeid(Type).name());
}
template <typename Type1, typename Type2>
diff --git a/source/core/StarColor.cpp b/source/core/StarColor.cpp
index 915620d..e0d6842 100644
--- a/source/core/StarColor.cpp
+++ b/source/core/StarColor.cpp
@@ -221,7 +221,7 @@ Color::Color(const String& name) {
if (i != NamedColors.end())
*this = i->second;
else
- throw ColorException(strf("Named color %s not found", name), false);
+ throw ColorException(strf("Named color {} not found", name), false);
}
}
@@ -622,7 +622,7 @@ Vec4B Color::hexToVec4B(StringView s) {
} else if (s.utf8Size() == 8) {
hexDecode(s.utf8Ptr(), 8, (char*)cbytes.data(), 4);
} else {
- throw ColorException(strf("Improper size for hex string '%s' in Color::hexToVec4B", s), false);
+ throw ColorException(strf("Improper size for hex string '{}' in Color::hexToVec4B", s), false);
}
return Vec4B(move(cbytes));
diff --git a/source/core/StarCompression.cpp b/source/core/StarCompression.cpp
index e8d282c..2aaf17f 100644
--- a/source/core/StarCompression.cpp
+++ b/source/core/StarCompression.cpp
@@ -23,7 +23,7 @@ void compressData(ByteArray const& in, ByteArray& out, CompressionLevel compress
strm.opaque = Z_NULL;
int deflate_res = deflateInit(&strm, compression);
if (deflate_res != Z_OK)
- throw IOException(strf("Failed to initialise deflate (%d)", deflate_res));
+ throw IOException(strf("Failed to initialise deflate ({})", deflate_res));
strm.next_in = (unsigned char*)in.ptr();
strm.avail_in = in.size();
@@ -40,7 +40,7 @@ void compressData(ByteArray const& in, ByteArray& out, CompressionLevel compress
deflateEnd(&strm);
if (deflate_res != Z_STREAM_END)
- throw IOException(strf("Internal error in uncompressData, deflate_res is %s", deflate_res));
+ throw IOException(strf("Internal error in uncompressData, deflate_res is {}", deflate_res));
out.append((char const*)temp_buffer, BUFSIZE - strm.avail_out);
}
@@ -66,7 +66,7 @@ void uncompressData(ByteArray const& in, ByteArray& out) {
strm.opaque = Z_NULL;
int inflate_res = inflateInit(&strm);
if (inflate_res != Z_OK)
- throw IOException(strf("Failed to initialise inflate (%d)", inflate_res));
+ throw IOException(strf("Failed to initialise inflate ({})", inflate_res));
strm.next_in = (unsigned char*)in.ptr();
strm.avail_in = in.size();
@@ -86,7 +86,7 @@ void uncompressData(ByteArray const& in, ByteArray& out) {
inflateEnd(&strm);
if (inflate_res != Z_STREAM_END)
- throw IOException(strf("Internal error in uncompressData, inflate_res is %s", inflate_res));
+ throw IOException(strf("Internal error in uncompressData, inflate_res is {}", inflate_res));
out.append((char const*)temp_buffer, BUFSIZE - strm.avail_out);
}
@@ -134,7 +134,7 @@ void CompressedFile::seek(StreamOffset offset, IOSeek seekMode) {
StreamOffset endPos = pos();
if (retCode < 0) {
- throw IOException::format("Seek error: %s", gzerror((gzFile)m_file, 0));
+ throw IOException::format("Seek error: {}", gzerror((gzFile)m_file, 0));
} else if ((seekMode == IOSeek::Relative && begPos + offset != endPos)
|| (seekMode == IOSeek::Absolute && offset != endPos)) {
throw EofException("Error, unexpected end of file found");
@@ -153,7 +153,7 @@ size_t CompressedFile::read(char* data, size_t len) {
if (ret == 0)
throw EofException("Error, unexpected end of file found");
else if (ret == -1)
- throw IOException::format("Read error: %s", gzerror((gzFile)m_file, 0));
+ throw IOException::format("Read error: {}", gzerror((gzFile)m_file, 0));
else
return (size_t)ret;
}
@@ -164,7 +164,7 @@ size_t CompressedFile::write(const char* data, size_t len) {
int ret = gzwrite((gzFile)m_file, data, len);
if (ret == 0)
- throw IOException::format("Write error: %s", gzerror((gzFile)m_file, 0));
+ throw IOException::format("Write error: {}", gzerror((gzFile)m_file, 0));
else
return (size_t)ret;
}
@@ -210,7 +210,7 @@ void CompressedFile::open(IOMode mode) {
m_file = gzopen(m_filename.utf8Ptr(), modeString.utf8Ptr());
if (!m_file)
- throw IOException::format("Cannot open filename '%s'", m_filename);
+ throw IOException::format("Cannot open filename '{}'", m_filename);
}
void CompressedFile::close() {
diff --git a/source/core/StarException_unix.cpp b/source/core/StarException_unix.cpp
index 578c0b4..71ffd2b 100644
--- a/source/core/StarException_unix.cpp
+++ b/source/core/StarException_unix.cpp
@@ -112,23 +112,23 @@ OutputProxy outputException(std::exception const& e, bool fullStacktrace) {
}
void printStack(char const* message) {
- Logger::info("Stack Trace (%s)...\n%s", message, outputStack(captureStack()));
+ Logger::info("Stack Trace ({})...\n{}", message, outputStack(captureStack()));
}
void fatalError(char const* message, bool showStackTrace) {
if (showStackTrace)
- Logger::error("Fatal Error: %s\n%s", message, outputStack(captureStack()));
+ Logger::error("Fatal Error: {}\n{}", message, outputStack(captureStack()));
else
- Logger::error("Fatal Error: %s", message);
+ Logger::error("Fatal Error: {}", message);
std::abort();
}
void fatalException(std::exception const& e, bool showStackTrace) {
if (showStackTrace)
- Logger::error("Fatal Exception caught: %s\nCaught at:\n%s", outputException(e, true), outputStack(captureStack()));
+ Logger::error("Fatal Exception caught: {}\nCaught at:\n{}", outputException(e, true), outputStack(captureStack()));
else
- Logger::error("Fatal Exception caught: %s", outputException(e, showStackTrace));
+ Logger::error("Fatal Exception caught: {}", outputException(e, showStackTrace));
std::abort();
}
diff --git a/source/core/StarException_windows.cpp b/source/core/StarException_windows.cpp
index 7fd386c..54254d4 100644
--- a/source/core/StarException_windows.cpp
+++ b/source/core/StarException_windows.cpp
@@ -127,9 +127,9 @@ OutputProxy outputStack(StackCapture stack) {
symbol->MaxNameLen = MAX_SYM_NAME;
DWORD64 displacement = 0;
- format(os, "[%i] %p", i, stack.first[i]);
+ format(os, "[{}] {}", i, (void*)stack.first[i]);
if (SymFromAddr(process, stack.first[i], &displacement, symbol))
- format(os, " %s", symbol->Name);
+ format(os, " {}", symbol->Name);
if (i + 1 < stack.second)
os << std::endl;
@@ -224,7 +224,7 @@ OutputProxy outputException(std::exception const& e, bool fullStacktrace) {
}
void printStack(char const* message) {
- Logger::info("Stack Trace (%s)...\n%s", message, outputStack(captureStack()));
+ Logger::info("Stack Trace ({})...\n{}", message, outputStack(captureStack()));
}
void fatalError(char const* message, bool showStackTrace) {
diff --git a/source/core/StarFile.cpp b/source/core/StarFile.cpp
index 738a088..ec09ff7 100644
--- a/source/core/StarFile.cpp
+++ b/source/core/StarFile.cpp
@@ -104,8 +104,8 @@ void File::overwriteFileWithRename(String const& data, String const& filename, S
void File::backupFileInSequence(String const& targetFile, unsigned maximumBackups, String const& backupExtensionPrefix) {
for (unsigned i = maximumBackups; i > 0; --i) {
- String curExtension = i == 1 ? "" : strf("%s%s", backupExtensionPrefix, i - 1);
- String nextExtension = strf("%s%s", backupExtensionPrefix, i);
+ String curExtension = i == 1 ? "" : strf("{}{}", backupExtensionPrefix, i - 1);
+ String nextExtension = strf("{}{}", backupExtensionPrefix, i);
if (File::isFile(targetFile + curExtension))
File::copy(targetFile + curExtension, targetFile + nextExtension);
diff --git a/source/core/StarFile_unix.cpp b/source/core/StarFile_unix.cpp
index aa22bc8..abc9fe0 100644
--- a/source/core/StarFile_unix.cpp
+++ b/source/core/StarFile_unix.cpp
@@ -46,19 +46,19 @@ String File::currentDirectory() {
void File::changeDirectory(const String& dirName) {
if (::chdir(dirName.utf8Ptr()) != 0)
- throw IOException(strf("could not change directory to %s", dirName));
+ throw IOException(strf("could not change directory to {}", dirName));
}
void File::makeDirectory(String const& dirName) {
if (::mkdir(dirName.utf8Ptr(), 0777) != 0)
- throw IOException(strf("could not create directory '%s', %s", dirName, strerror(errno)));
+ throw IOException(strf("could not create directory '{}', {}", dirName, strerror(errno)));
}
List<pair<String, bool>> File::dirList(const String& dirName, bool skipDots) {
List<std::pair<String, bool>> fileList;
DIR* directory = ::opendir(dirName.utf8Ptr());
if (directory == NULL)
- throw IOException::format("dirList failed on dir: '%s'", dirName);
+ throw IOException::format("dirList failed on dir: '{}'", dirName);
for (dirent* entry = ::readdir(directory); entry != NULL; entry = ::readdir(directory)) {
String entryString = entry->d_name;
@@ -113,13 +113,13 @@ String File::fullPath(const String& fileName) {
char buffer[PATH_MAX];
if (::realpath(fileName.utf8Ptr(), buffer) == NULL)
- throw IOException::format("realpath failed on file: '%s' problem path was: '%s'", fileName, buffer);
+ throw IOException::format("realpath failed on file: '{}' problem path was: '{}'", fileName, buffer);
return String(buffer);
}
String File::temporaryFileName() {
- return relativeTo(P_tmpdir, strf("starbound.tmpfile.%s", hexEncode(Random::randBytes(16))));
+ return relativeTo(P_tmpdir, strf("starbound.tmpfile.{}", hexEncode(Random::randBytes(16))));
}
FilePtr File::temporaryFile() {
@@ -131,16 +131,16 @@ FilePtr File::ephemeralFile() {
ByteArray path = ByteArray::fromCStringWithNull(relativeTo(P_tmpdir, "starbound.tmpfile.XXXXXXXX").utf8Ptr());
auto res = mkstemp(path.ptr());
if (res < 0)
- throw IOException::format("tmpfile error: %s", strerror(errno));
+ throw IOException::format("tmpfile error: {}", strerror(errno));
if (::unlink(path.ptr()) < 0)
- throw IOException::format("Could not remove mkstemp file when creating ephemeralFile: %s", strerror(errno));
+ throw IOException::format("Could not remove mkstemp file when creating ephemeralFile: {}", strerror(errno));
file->m_file = handleFromFd(res);
file->setMode(IOMode::ReadWrite);
return file;
}
String File::temporaryDirectory() {
- String dirname = relativeTo(P_tmpdir, strf("starbound.tmpdir.%s", hexEncode(Random::randBytes(16))));
+ String dirname = relativeTo(P_tmpdir, strf("starbound.tmpdir.{}", hexEncode(Random::randBytes(16))));
makeDirectory(dirname);
return dirname;
}
@@ -171,12 +171,12 @@ bool File::isDirectory(String const& path) {
void File::remove(String const& filename) {
if (::remove(filename.utf8Ptr()) < 0)
- throw IOException::format("remove error: %s", strerror(errno));
+ throw IOException::format("remove error: {}", strerror(errno));
}
void File::rename(String const& source, String const& target) {
if (::rename(source.utf8Ptr(), target.utf8Ptr()) < 0)
- throw IOException::format("rename error: %s", strerror(errno));
+ throw IOException::format("rename error: {}", strerror(errno));
}
void File::overwriteFileWithRename(char const* data, size_t len, String const& filename, String const& newSuffix) {
@@ -200,11 +200,11 @@ void* File::fopen(char const* filename, IOMode mode) {
int fd = ::open(filename, oflag, 0666);
if (fd < 0)
- throw IOException::format("Error opening file '%s', error: %s", filename, strerror(errno));
+ throw IOException::format("Error opening file '{}', error: {}", filename, strerror(errno));
if (mode & IOMode::Append) {
if (lseek(fd, 0, SEEK_END) < 0)
- throw IOException::format("Error opening file '%s', cannot seek: %s", filename, strerror(errno));
+ throw IOException::format("Error opening file '{}', cannot seek: {}", filename, strerror(errno));
}
return handleFromFd(fd);
@@ -221,7 +221,7 @@ void File::fseek(void* f, StreamOffset offset, IOSeek seekMode) {
retCode = lseek(fd, offset, SEEK_END);
if (retCode < 0)
- throw IOException::format("Seek error: %s", strerror(errno));
+ throw IOException::format("Seek error: {}", strerror(errno));
}
StreamOffset File::ftell(void* f) {
@@ -237,7 +237,7 @@ size_t File::fread(void* file, char* data, size_t len) {
if (ret < 0) {
if (errno == EAGAIN || errno == EINTR)
return 0;
- throw IOException::format("Read error: %s", strerror(errno));
+ throw IOException::format("Read error: {}", strerror(errno));
} else {
return ret;
}
@@ -252,7 +252,7 @@ size_t File::fwrite(void* file, char const* data, size_t len) {
if (ret < 0) {
if (errno == EAGAIN || errno == EINTR)
return 0;
- throw IOException::format("Write error: %s", strerror(errno));
+ throw IOException::format("Write error: {}", strerror(errno));
} else {
return ret;
}
@@ -269,7 +269,7 @@ void File::fsync(void* file) {
void File::fclose(void* file) {
if (::close(fdFromHandle(file)) < 0)
- throw IOException::format("Close error: %s", strerror(errno));
+ throw IOException::format("Close error: {}", strerror(errno));
}
StreamOffset File::fsize(void* file) {
@@ -289,7 +289,7 @@ size_t File::pwrite(void* file, char const* data, size_t len, StreamOffset posit
void File::resize(void* f, StreamOffset size) {
if (::ftruncate(fdFromHandle(f), size) < 0)
- throw IOException::format("resize error: %s", strerror(errno));
+ throw IOException::format("resize error: {}", strerror(errno));
}
}
diff --git a/source/core/StarFile_windows.cpp b/source/core/StarFile_windows.cpp
index bb13ffc..0b5c286 100644
--- a/source/core/StarFile_windows.cpp
+++ b/source/core/StarFile_windows.cpp
@@ -42,13 +42,13 @@ String File::currentDirectory() {
void File::changeDirectory(const String& dirName) {
if (!SetCurrentDirectoryW(stringToUtf16(dirName).get()))
- throw IOException(strf("could not change directory to %s", dirName));
+ throw IOException(strf("could not change directory to {}", dirName));
}
void File::makeDirectory(String const& dirName) {
if (CreateDirectoryW(stringToUtf16(dirName).get(), NULL) == 0) {
auto error = GetLastError();
- throw IOException(strf("could not create directory '%s', %s", dirName, error));
+ throw IOException(strf("could not create directory '{}', {}", dirName, error));
}
}
@@ -85,9 +85,9 @@ String File::fullPath(const String& path) {
fullpath_size = GetFullPathNameW(stringToUtf16(path).get(), (DWORD)MAX_PATH, buffer, (WCHAR**)&lpszLastNamePart);
if (0 == fullpath_size)
- throw IOException::format("GetFullPathName failed on path: '%s'", path);
+ throw IOException::format("GetFullPathName failed on path: '{}'", path);
if (fullpath_size >= MAX_PATH)
- throw IOException::format("GetFullPathName failed on path: '%s'", path);
+ throw IOException::format("GetFullPathName failed on path: '{}'", path);
return utf16ToString(buffer);
}
@@ -99,7 +99,7 @@ List<std::pair<String, bool>> File::dirList(const String& dirName, bool skipDots
hFind = FindFirstFileW(stringToUtf16(File::relativeTo(dirName, "*")).get(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
- throw IOException(strf("Invalid file handle in dirList of '%s', error is %u", dirName, GetLastError()));
+ throw IOException(strf("Invalid file handle in dirList of '{}', error is %u", dirName, GetLastError()));
while (true) {
String entry = utf16ToString(findFileData.cFileName);
@@ -113,7 +113,7 @@ List<std::pair<String, bool>> File::dirList(const String& dirName, bool skipDots
FindClose(hFind);
if ((dwError != ERROR_NO_MORE_FILES) && (dwError != NO_ERROR))
- throw IOException(strf("FindNextFile error in dirList of '%s'. Error is %u", dirName, dwError));
+ throw IOException(strf("FindNextFile error in dirList of '{}'. Error is %u", dirName, dwError));
return fileList;
}
@@ -158,10 +158,10 @@ String File::temporaryFileName() {
WCHAR tempPath[MAX_PATH];
if (!GetTempPathW(MAX_PATH, tempPath)) {
auto error = GetLastError();
- throw IOException(strf("Could not call GetTempPath %s", error));
+ throw IOException(strf("Could not call GetTempPath {}", error));
}
- return relativeTo(utf16ToString(tempPath), strf("starbound.tmpfile.%s", hexEncode(Random::randBytes(16))));
+ return relativeTo(utf16ToString(tempPath), strf("starbound.tmpfile.{}", hexEncode(Random::randBytes(16))));
}
FilePtr File::temporaryFile() {
@@ -179,10 +179,10 @@ String File::temporaryDirectory() {
WCHAR tempPath[MAX_PATH];
if (!GetTempPathW(MAX_PATH, tempPath)) {
auto error = GetLastError();
- throw IOException(strf("Could not call GetTempPath %s", error));
+ throw IOException(strf("Could not call GetTempPath {}", error));
}
- String dirname = relativeTo(utf16ToString(tempPath), strf("starbound.tmpdir.%s", hexEncode(Random::randBytes(16))));
+ String dirname = relativeTo(utf16ToString(tempPath), strf("starbound.tmpdir.{}", hexEncode(Random::randBytes(16))));
makeDirectory(dirname);
return dirname;
}
@@ -191,11 +191,11 @@ void File::remove(String const& filename) {
if (isDirectory(filename)) {
if (!RemoveDirectoryW(stringToUtf16(filename).get())) {
auto error = GetLastError();
- throw IOException(strf("Rename error: %s", error));
+ throw IOException(strf("Rename error: {}", error));
}
} else if (::_wremove(stringToUtf16(filename).get()) < 0) {
auto error = errno;
- throw IOException::format("remove error: %s", strerror(error));
+ throw IOException::format("remove error: {}", strerror(error));
}
}
@@ -207,22 +207,22 @@ void File::rename(String const& source, String const& target) {
if (!DeleteFileW(stringToUtf16(temp).get())) {
auto error = GetLastError();
if (error != ERROR_FILE_NOT_FOUND)
- throw IOException(strf("error deleting existing temp file: %s", error));
+ throw IOException(strf("error deleting existing temp file: {}", error));
}
if (!MoveFileExW(stringToUtf16(target).get(), stringToUtf16(temp).get(), MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
auto error = GetLastError();
- throw IOException(strf("error temporary file '%s': %s", temp, GetLastError()));
+ throw IOException(strf("error temporary file '{}': {}", temp, GetLastError()));
}
}
if (!MoveFileExW(stringToUtf16(source).get(), stringToUtf16(target).get(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
auto error = GetLastError();
- throw IOException(strf("Rename error: %s", error));
+ throw IOException(strf("Rename error: {}", error));
}
if (replace && !DeleteFileW(stringToUtf16(temp).get())) {
auto error = GetLastError();
- throw IOException(strf("error deleting temp file '%s': %s", temp, GetLastError()));
+ throw IOException(strf("error deleting temp file '{}': {}", temp, GetLastError()));
}
}
@@ -266,19 +266,19 @@ void* File::fopen(char const* filename, IOMode mode) {
creationDisposition, 0, NULL);
if (file == INVALID_HANDLE_VALUE)
- throw IOException::format("could not open file '%s' %s", filename, GetLastError());
+ throw IOException::format("could not open file '{}' {}", filename, GetLastError());
LARGE_INTEGER szero;
szero.QuadPart = 0;
if (!SetFilePointerEx(file, szero, NULL, 0)) {
CloseHandle(file);
- throw IOException::format("could not set file pointer in fopen '%s' %s", filename, GetLastError());
+ throw IOException::format("could not set file pointer in fopen '{}' {}", filename, GetLastError());
}
if (mode & IOMode::Truncate) {
if (!SetEndOfFile(file)) {
CloseHandle(file);
- throw IOException::format("could not set end of file in fopen '%s' %s", filename, GetLastError());
+ throw IOException::format("could not set end of file in fopen '{}' {}", filename, GetLastError());
}
}
@@ -286,11 +286,11 @@ void* File::fopen(char const* filename, IOMode mode) {
LARGE_INTEGER size;
if (GetFileSizeEx(file, &size) == 0) {
CloseHandle(file);
- throw IOException::format("could not get file size in fopen '%s' %s", filename, GetLastError());
+ throw IOException::format("could not get file size in fopen '{}' {}", filename, GetLastError());
}
if (!SetFilePointerEx(file, size, NULL, 0)) {
CloseHandle(file);
- throw IOException::format("could not set file pointer in fopen '%s' %s", filename, GetLastError());
+ throw IOException::format("could not set file pointer in fopen '{}' {}", filename, GetLastError());
}
}
@@ -331,7 +331,7 @@ size_t File::fread(void* f, char* data, size_t len) {
if (ret == 0) {
auto err = GetLastError();
if (err != ERROR_IO_PENDING)
- throw IOException::format("read error %s", err);
+ throw IOException::format("read error {}", err);
}
return numRead;
@@ -348,7 +348,7 @@ size_t File::fwrite(void* f, char const* data, size_t len) {
if (ret == 0) {
auto err = GetLastError();
if (err != ERROR_IO_PENDING)
- throw IOException::format("write error %s", err);
+ throw IOException::format("write error {}", err);
}
return numWritten;
@@ -357,7 +357,7 @@ size_t File::fwrite(void* f, char const* data, size_t len) {
void File::fsync(void* f) {
HANDLE file = (HANDLE)f;
if (FlushFileBuffers(file) == 0)
- throw IOException::format("fsync error %s", GetLastError());
+ throw IOException::format("fsync error {}", GetLastError());
}
void File::fclose(void* f) {
@@ -369,7 +369,7 @@ StreamOffset File::fsize(void* f) {
HANDLE file = (HANDLE)f;
LARGE_INTEGER size;
if (GetFileSizeEx(file, &size) == 0)
- throw IOException::format("could not get file size in fsize %s", GetLastError());
+ throw IOException::format("could not get file size in fsize {}", GetLastError());
return size.QuadPart;
}
@@ -381,7 +381,7 @@ size_t File::pread(void* f, char* data, size_t len, StreamOffset position) {
if (ret == 0) {
auto err = GetLastError();
if (err != ERROR_IO_PENDING)
- throw IOException::format("pread error %s", err);
+ throw IOException::format("pread error {}", err);
}
return numRead;
@@ -395,7 +395,7 @@ size_t File::pwrite(void* f, char const* data, size_t len, StreamOffset position
if (ret == 0) {
auto err = GetLastError();
if (err != ERROR_IO_PENDING)
- throw IOException::format("pwrite error %s", err);
+ throw IOException::format("pwrite error {}", err);
}
return numWritten;
diff --git a/source/core/StarFont.cpp b/source/core/StarFont.cpp
index e16a2be..6308784 100644
--- a/source/core/StarFont.cpp
+++ b/source/core/StarFont.cpp
@@ -66,7 +66,7 @@ void Font::setPixelSize(unsigned pixelSize) {
return;
if (FT_Set_Pixel_Sizes(m_fontImpl->face, pixelSize, 0))
- throw FontException(strf("Cannot set font pixel size to: %s", pixelSize));
+ throw FontException(strf("Cannot set font pixel size to: {}", pixelSize));
m_pixelSize = pixelSize;
}
diff --git a/source/core/StarFormattedJson.cpp b/source/core/StarFormattedJson.cpp
index f31f3ba..d7bd8c7 100644
--- a/source/core/StarFormattedJson.cpp
+++ b/source/core/StarFormattedJson.cpp
@@ -105,21 +105,21 @@ Json const& FormattedJson::toJson() const {
FormattedJson FormattedJson::get(String const& key) const {
if (type() != Json::Type::Object)
- throw JsonException::format("Cannot call get with key on FormattedJson type %s, must be Object type", typeName());
+ throw JsonException::format("Cannot call get with key on FormattedJson type {}, must be Object type", typeName());
Maybe<pair<ElementLocation, ElementLocation>> entry = m_objectEntryLocations.maybe(key);
if (entry.isNothing())
- throw JsonException::format("No such key in FormattedJson::get(\"%s\")", key);
+ throw JsonException::format("No such key in FormattedJson::get(\"{}\")", key);
return getFormattedJson(entry->second);
}
FormattedJson FormattedJson::get(size_t index) const {
if (type() != Json::Type::Array)
- throw JsonException::format("Cannot call get with index on FormattedJson type %s, must be Array type", typeName());
+ throw JsonException::format("Cannot call get with index on FormattedJson type {}, must be Array type", typeName());
if (index >= m_arrayElementLocations.size())
- throw JsonException::format("FormattedJson::get(%s) out of range", index);
+ throw JsonException::format("FormattedJson::get({}) out of range", index);
ElementLocation loc = m_arrayElementLocations.at(index);
return getFormattedJson(loc);
@@ -263,14 +263,14 @@ FormattedJson FormattedJson::prepend(String const& key, FormattedJson const& val
FormattedJson FormattedJson::insertBefore(String const& key, FormattedJson const& value, String const& beforeKey) const {
if (!m_objectEntryLocations.contains(beforeKey))
- throw JsonException::format("Cannot insert before key \"%s\", which does not exist", beforeKey);
+ throw JsonException::format("Cannot insert before key \"{}\", which does not exist", beforeKey);
ElementLocation loc = m_objectEntryLocations.get(beforeKey).first;
return objectInsert(key, value, loc);
}
FormattedJson FormattedJson::insertAfter(String const& key, FormattedJson const& value, String const& afterKey) const {
if (!m_objectEntryLocations.contains(afterKey))
- throw JsonException::format("Cannot insert after key \"%s\", which does not exist", afterKey);
+ throw JsonException::format("Cannot insert after key \"{}\", which does not exist", afterKey);
ElementLocation loc = m_objectEntryLocations.get(afterKey).second;
return objectInsert(key, value, loc + 1);
}
@@ -303,7 +303,7 @@ void removeValueFromArray(List<JsonElement>& elements, size_t loc) {
FormattedJson FormattedJson::eraseKey(String const& key) const {
if (type() != Json::Type::Object)
- throw JsonException::format("Cannot call erase with key on FormattedJson type %s, must be Object type", typeName());
+ throw JsonException::format("Cannot call erase with key on FormattedJson type {}, must be Object type", typeName());
Maybe<pair<ElementLocation, ElementLocation>> maybeEntry = m_objectEntryLocations.maybe(key);
if (maybeEntry.isNothing())
@@ -319,10 +319,10 @@ FormattedJson FormattedJson::eraseKey(String const& key) const {
FormattedJson FormattedJson::insert(size_t index, FormattedJson const& value) const {
if (type() != Json::Type::Array)
throw JsonException::format(
- "Cannot call insert with index on FormattedJson type %s, must be Array type", typeName());
+ "Cannot call insert with index on FormattedJson type {}, must be Array type", typeName());
if (index > m_arrayElementLocations.size())
- throw JsonException::format("FormattedJson::insert(%s) out of range", index);
+ throw JsonException::format("FormattedJson::insert({}) out of range", index);
ElementList elements = m_elements;
ElementLocation insertPosition = elements.size();
@@ -335,7 +335,7 @@ FormattedJson FormattedJson::insert(size_t index, FormattedJson const& value) co
FormattedJson FormattedJson::append(FormattedJson const& value) const {
if (type() != Json::Type::Array)
- throw JsonException::format("Cannot call append on FormattedJson type %s, must be Array type", typeName());
+ throw JsonException::format("Cannot call append on FormattedJson type {}, must be Array type", typeName());
ElementList elements = m_elements;
insertWithCommaAndFormatting(elements, elements.size(), true, {ValueElement{value}});
@@ -344,10 +344,10 @@ FormattedJson FormattedJson::append(FormattedJson const& value) const {
FormattedJson FormattedJson::set(size_t index, FormattedJson const& value) const {
if (type() != Json::Type::Array)
- throw JsonException::format("Cannot call set with index on FormattedJson type %s, must be Array type", typeName());
+ throw JsonException::format("Cannot call set with index on FormattedJson type {}, must be Array type", typeName());
if (index >= m_arrayElementLocations.size())
- throw JsonException::format("FormattedJson::set(%s) out of range", index);
+ throw JsonException::format("FormattedJson::set({}) out of range", index);
ElementLocation loc = m_arrayElementLocations.at(index);
ElementList elements = m_elements;
@@ -357,10 +357,10 @@ FormattedJson FormattedJson::set(size_t index, FormattedJson const& value) const
FormattedJson FormattedJson::eraseIndex(size_t index) const {
if (type() != Json::Type::Array)
- throw JsonException::format("Cannot call set with index on FormattedJson type %s, must be Array type", typeName());
+ throw JsonException::format("Cannot call set with index on FormattedJson type {}, must be Array type", typeName());
if (index >= m_arrayElementLocations.size())
- throw JsonException::format("FormattedJson::eraseIndex(%s) out of range", index);
+ throw JsonException::format("FormattedJson::eraseIndex({}) out of range", index);
ElementLocation loc = m_arrayElementLocations.at(index);
ElementList elements = m_elements;
@@ -390,7 +390,7 @@ String FormattedJson::typeName() const {
String FormattedJson::toFormattedDouble() const {
if (!isType(Json::Type::Float))
- throw JsonException::format("Cannot call toFormattedDouble on Json type %s, must be Float", typeName());
+ throw JsonException::format("Cannot call toFormattedDouble on Json type {}, must be Float", typeName());
if (m_formatting.isValid())
return *m_formatting;
return toJson().repr();
@@ -398,7 +398,7 @@ String FormattedJson::toFormattedDouble() const {
String FormattedJson::toFormattedInt() const {
if (!isType(Json::Type::Int))
- throw JsonException::format("Cannot call toFormattedInt on Json type %s, must be Int", typeName());
+ throw JsonException::format("Cannot call toFormattedInt on Json type {}, must be Int", typeName());
if (m_formatting.isValid())
return *m_formatting;
return toJson().repr();
@@ -454,7 +454,7 @@ FormattedJson FormattedJson::array(ElementList const& elements) {
FormattedJson FormattedJson::objectInsert(String const& key, FormattedJson const& value, ElementLocation loc) const {
if (type() != Json::Type::Object)
- throw JsonException::format("Cannot call set with key on FormattedJson type %s, must be Object type", typeName());
+ throw JsonException::format("Cannot call set with key on FormattedJson type {}, must be Object type", typeName());
Maybe<pair<ElementLocation, ElementLocation>> maybeEntry = m_objectEntryLocations.maybe(key);
if (maybeEntry.isValid()) {
diff --git a/source/core/StarHostAddress.cpp b/source/core/StarHostAddress.cpp
index f65f179..5459a7e 100644
--- a/source/core/StarHostAddress.cpp
+++ b/source/core/StarHostAddress.cpp
@@ -133,7 +133,7 @@ void HostAddress::set(String const& address) {
hints.ai_flags = AI_ADDRCONFIG;
if (::getaddrinfo(address.utf8Ptr(), NULL, &hints, &result) != 0)
- throw NetworkException(strf("Failed to determine address for '%s' (%s)", address, netErrorString()));
+ throw NetworkException(strf("Failed to determine address for '{}' ({})", address, netErrorString()));
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
NetworkMode mode;
@@ -171,12 +171,12 @@ void HostAddress::set(NetworkMode mode, uint8_t const* addr) {
std::ostream& operator<<(std::ostream& os, HostAddress const& address) {
switch (address.mode()) {
case NetworkMode::IPv4:
- format(os, "%d.%d.%d.%d", address.octet(0), address.octet(1), address.octet(2), address.octet(3));
+ format(os, "{}.{}.{}.{}", address.octet(0), address.octet(1), address.octet(2), address.octet(3));
break;
case NetworkMode::IPv6:
format(os,
- "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
+ "{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}",
address.octet(0),
address.octet(1),
address.octet(2),
@@ -196,7 +196,7 @@ std::ostream& operator<<(std::ostream& os, HostAddress const& address) {
break;
default:
- throw NetworkException(strf("Unknown address mode (%d)", (int)address.mode()));
+ throw NetworkException(strf("Unknown address mode ({})", (int)address.mode()));
}
return os;
}
@@ -224,7 +224,7 @@ Either<String, HostAddressWithPort> HostAddressWithPort::lookupWithPort(String c
auto portNum = maybeLexicalCast<uint16_t>(port);
if (!portNum)
- return makeLeft(strf("Could not parse port portion of HostAddressWithPort '%s'", port));
+ return makeLeft(strf("Could not parse port portion of HostAddressWithPort '{}'", port));
auto hostAddress = HostAddress::lookup(host);
if (hostAddress.isLeft())
diff --git a/source/core/StarIODevice.cpp b/source/core/StarIODevice.cpp
index 1274e89..2b79bb3 100644
--- a/source/core/StarIODevice.cpp
+++ b/source/core/StarIODevice.cpp
@@ -42,7 +42,7 @@ void IODevice::writeFull(char const* data, size_t len) {
void IODevice::open(IOMode mode) {
if (mode != m_mode)
- throw IOException::format("Cannot reopen device '%s", deviceName());
+ throw IOException::format("Cannot reopen device '{}", deviceName());
}
void IODevice::close() {
@@ -52,7 +52,7 @@ void IODevice::close() {
void IODevice::sync() {}
String IODevice::deviceName() const {
- return strf("IODevice <%s>", (void*)this);
+ return strf("IODevice <{}>", (void*)this);
}
bool IODevice::atEnd() {
diff --git a/source/core/StarIdMap.hpp b/source/core/StarIdMap.hpp
index 15946da..1f97c55 100644
--- a/source/core/StarIdMap.hpp
+++ b/source/core/StarIdMap.hpp
@@ -102,7 +102,7 @@ auto IdMapWrapper<BaseMap>::nextId() -> IdType {
template <typename BaseMap>
void IdMapWrapper<BaseMap>::add(IdType id, MappedType mappedType) {
if (!BaseMap::insert(make_pair(move(id), move(mappedType))).second)
- throw IdMapException::format("IdMapWrapper::add(id, value) called with pre-existing id '%s'", outputAny(id));
+ throw IdMapException::format("IdMapWrapper::add(id, value) called with pre-existing id '{}'", outputAny(id));
}
template <typename BaseMap>
diff --git a/source/core/StarImage.cpp b/source/core/StarImage.cpp
index bd3e838..1494503 100644
--- a/source/core/StarImage.cpp
+++ b/source/core/StarImage.cpp
@@ -7,7 +7,7 @@ namespace Star {
Image Image::readPng(IODevicePtr device) {
auto logPngError = [](png_structp png_ptr, png_const_charp c) {
- Logger::debug("PNG error in file: '%s', %s", (char*)png_get_error_ptr(png_ptr), c);
+ Logger::debug("PNG error in file: '{}', {}", (char*)png_get_error_ptr(png_ptr), c);
};
auto readPngData = [](png_structp pngPtr, png_bytep data, png_size_t length) {
@@ -19,7 +19,7 @@ Image Image::readPng(IODevicePtr device) {
device->readFull((char*)header, sizeof(header));
if (png_sig_cmp(header, 0, sizeof(header)))
- throw ImageException(strf("File %s is not a png image!", device->deviceName()));
+ throw ImageException(strf("File {} is not a png image!", device->deviceName()));
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr)
@@ -94,7 +94,7 @@ Image Image::readPng(IODevicePtr device) {
if (bitdepth != 8 || (channels != 3 && channels != 4)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
- throw ImageException(strf("Unsupported PNG pixel format in file %s", device->deviceName()));
+ throw ImageException(strf("Unsupported PNG pixel format in file {}", device->deviceName()));
}
Image image(img_width, img_height, channels == 3 ? PixelFormat::RGB24 : PixelFormat::RGBA32);
@@ -112,7 +112,7 @@ Image Image::readPng(IODevicePtr device) {
tuple<Vec2U, PixelFormat> Image::readPngMetadata(IODevicePtr device) {
auto logPngError = [](png_structp png_ptr, png_const_charp c) {
- Logger::debug("PNG error in file: '%s', %s", (char*)png_get_error_ptr(png_ptr), c);
+ Logger::debug("PNG error in file: '{}', {}", (char*)png_get_error_ptr(png_ptr), c);
};
auto readPngData = [](png_structp pngPtr, png_bytep data, png_size_t length) {
@@ -124,7 +124,7 @@ tuple<Vec2U, PixelFormat> Image::readPngMetadata(IODevicePtr device) {
device->readFull((char*)header, sizeof(header));
if (png_sig_cmp(header, 0, sizeof(header)))
- throw ImageException(strf("File %s is not a png image!", device->deviceName()));
+ throw ImageException(strf("File {} is not a png image!", device->deviceName()));
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr)
@@ -267,7 +267,7 @@ void Image::reset(unsigned width, unsigned height, Maybe<PixelFormat> pf) {
newData = (uint8_t*)Star::realloc(m_data, imageSize);
if (!newData)
- throw MemoryException::format("Could not allocate memory for new Image size %s\n", imageSize);
+ throw MemoryException::format("Could not allocate memory for new Image size {}\n", imageSize);
m_data = newData;
memset(m_data, 0, imageSize);
@@ -316,7 +316,7 @@ void Image::fillRect(Vec2U const& pos, Vec2U const& size, Vec4B const& c) {
void Image::set(Vec2U const& pos, Vec4B const& c) {
if (pos[0] >= m_width || pos[1] >= m_height) {
- throw ImageException(strf("%s out of range in Image::set", pos));
+ throw ImageException(strf("{} out of range in Image::set", pos));
} else if (bytesPerPixel() == 4) {
size_t offset = pos[1] * m_width * 4 + pos[0] * 4;
m_data[offset] = c[0];
@@ -333,7 +333,7 @@ void Image::set(Vec2U const& pos, Vec4B const& c) {
void Image::set(Vec2U const& pos, Vec3B const& c) {
if (pos[0] >= m_width || pos[1] >= m_height) {
- throw ImageException(strf("%s out of range in Image::set", pos));
+ throw ImageException(strf("{} out of range in Image::set", pos));
} else if (bytesPerPixel() == 4) {
size_t offset = pos[1] * m_width * 4 + pos[0] * 4;
m_data[offset] = c[0];
@@ -351,7 +351,7 @@ void Image::set(Vec2U const& pos, Vec3B const& c) {
Vec4B Image::get(Vec2U const& pos) const {
Vec4B c;
if (pos[0] >= m_width || pos[1] >= m_height) {
- throw ImageException(strf("%s out of range in Image::get", pos));
+ throw ImageException(strf("{} out of range in Image::get", pos));
} else if (bytesPerPixel() == 4) {
size_t offset = pos[1] * m_width * 4 + pos[0] * 4;
c[0] = m_data[offset];
@@ -422,7 +422,7 @@ Vec4B Image::clamprgb(Vec2I const& pos) const {
Image Image::subImage(Vec2U const& pos, Vec2U const& size) const {
if (pos[0] + size[0] > m_width || pos[1] + size[1] > m_height)
- throw ImageException(strf("call to subImage with pos %s size %s out of image bounds (%s, %s)", pos, size, m_width, m_height));
+ throw ImageException(strf("call to subImage with pos {} size {} out of image bounds ({}, {})", pos, size, m_width, m_height));
Image sub(size[0], size[1], m_pixelFormat);
diff --git a/source/core/StarImageProcessing.cpp b/source/core/StarImageProcessing.cpp
index 2c79b58..bf4d01a 100644
--- a/source/core/StarImageProcessing.cpp
+++ b/source/core/StarImageProcessing.cpp
@@ -199,7 +199,7 @@ ImageOperation imageOperationFromString(StringView string) {
hexDecode(hexPtr, 8, c, 4);
}
else if (!which || (ptr != end && ++ptr != end))
- throw ImageOperationException(strf("Improper size for hex string '%s' in imageOperationFromString", StringView(hexPtr, hexLen)), false);
+ throw ImageOperationException(strf("Improper size for hex string '{}' in imageOperationFromString", StringView(hexPtr, hexLen)), false);
else // we're in A of A=B. In vanilla only A=B pairs are evaluated, so only throw an exception if B is also there.
return move(operation);
@@ -341,7 +341,7 @@ ImageOperation imageOperationFromString(StringView string) {
return FlipImageOperation{FlipImageOperation::FlipXY};
} else {
- throw ImageOperationException(strf("Could not recognize ImageOperation type %s", type), false);
+ throw ImageOperationException(strf("Could not recognize ImageOperation type {}", type), false);
}
} catch (OutOfRangeException const& e) {
throw ImageOperationException("Error reading ImageOperation", e);
@@ -352,52 +352,52 @@ ImageOperation imageOperationFromString(StringView string) {
String imageOperationToString(ImageOperation const& operation) {
if (auto op = operation.ptr<HueShiftImageOperation>()) {
- return strf("hueshift=%s", op->hueShiftAmount * 360.0f);
+ return strf("hueshift={}", op->hueShiftAmount * 360.0f);
} else if (auto op = operation.ptr<SaturationShiftImageOperation>()) {
- return strf("saturation=%s", op->saturationShiftAmount * 100.0f);
+ return strf("saturation={}", op->saturationShiftAmount * 100.0f);
} else if (auto op = operation.ptr<BrightnessMultiplyImageOperation>()) {
- return strf("brightness=%s", (op->brightnessMultiply - 1.0f) * 100.0f);
+ return strf("brightness={}", (op->brightnessMultiply - 1.0f) * 100.0f);
} else if (auto op = operation.ptr<FadeToColorImageOperation>()) {
- return strf("fade=%s=%s", Color::rgb(op->color).toHex(), op->amount);
+ return strf("fade={}={}", Color::rgb(op->color).toHex(), op->amount);
} else if (auto op = operation.ptr<ScanLinesImageOperation>()) {
- return strf("scanlines=%s=%s=%s=%s",
+ return strf("scanlines={}={}={}={}",
Color::rgb(op->fade1.color).toHex(),
op->fade1.amount,
Color::rgb(op->fade2.color).toHex(),
op->fade2.amount);
} else if (auto op = operation.ptr<SetColorImageOperation>()) {
- return strf("setcolor=%s", Color::rgb(op->color).toHex());
+ return strf("setcolor={}", Color::rgb(op->color).toHex());
} else if (auto op = operation.ptr<ColorReplaceImageOperation>()) {
String str = "replace";
for (auto const& pair : op->colorReplaceMap)
- str += strf(";%s=%s", Color::rgba(pair.first).toHex(), Color::rgba(pair.second).toHex());
+ str += strf(";{}={}", Color::rgba(pair.first).toHex(), Color::rgba(pair.second).toHex());
return str;
} else if (auto op = operation.ptr<AlphaMaskImageOperation>()) {
if (op->mode == AlphaMaskImageOperation::Additive)
- return strf("addmask=%s;%s;%s", op->maskImages.join("+"), op->offset[0], op->offset[1]);
+ return strf("addmask={};{};{}", op->maskImages.join("+"), op->offset[0], op->offset[1]);
else if (op->mode == AlphaMaskImageOperation::Subtractive)
- return strf("submask=%s;%s;%s", op->maskImages.join("+"), op->offset[0], op->offset[1]);
+ return strf("submask={};{};{}", op->maskImages.join("+"), op->offset[0], op->offset[1]);
} else if (auto op = operation.ptr<BlendImageOperation>()) {
if (op->mode == BlendImageOperation::Multiply)
- return strf("blendmult=%s;%s;%s", op->blendImages.join("+"), op->offset[0], op->offset[1]);
+ return strf("blendmult={};{};{}", op->blendImages.join("+"), op->offset[0], op->offset[1]);
else if (op->mode == BlendImageOperation::Screen)
- return strf("blendscreen=%s;%s;%s", op->blendImages.join("+"), op->offset[0], op->offset[1]);
+ return strf("blendscreen={};{};{}", op->blendImages.join("+"), op->offset[0], op->offset[1]);
} else if (auto op = operation.ptr<MultiplyImageOperation>()) {
- return strf("multiply=%s", Color::rgba(op->color).toHex());
+ return strf("multiply={}", Color::rgba(op->color).toHex());
} else if (auto op = operation.ptr<BorderImageOperation>()) {
if (op->outlineOnly)
- return strf("outline=%d;%s;%s", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex());
+ return strf("outline={};{};{}", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex());
else
- return strf("border=%d;%s;%s", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex());
+ return strf("border={};{};{}", op->pixels, Color::rgba(op->startColor).toHex(), Color::rgba(op->endColor).toHex());
} else if (auto op = operation.ptr<ScaleImageOperation>()) {
if (op->mode == ScaleImageOperation::Nearest)
- return strf("scalenearest=%s", op->scale);
+ return strf("scalenearest={}", op->scale);
else if (op->mode == ScaleImageOperation::Bilinear)
- return strf("scalebilinear=%s", op->scale);
+ return strf("scalebilinear={}", op->scale);
else if (op->mode == ScaleImageOperation::Bicubic)
- return strf("scalebicubic=%s", op->scale);
+ return strf("scalebicubic={}", op->scale);
} else if (auto op = operation.ptr<CropImageOperation>()) {
- return strf("crop=%s;%s;%s;%s", op->subset.xMin(), op->subset.xMax(), op->subset.yMin(), op->subset.yMax());
+ return strf("crop={};{};{};{}", op->subset.xMin(), op->subset.xMax(), op->subset.yMin(), op->subset.yMax());
} else if (auto op = operation.ptr<FlipImageOperation>()) {
if (op->mode == FlipImageOperation::FlipX)
return "flipx";
diff --git a/source/core/StarJson.cpp b/source/core/StarJson.cpp
index 9639ce4..2892e1c 100644
--- a/source/core/StarJson.cpp
+++ b/source/core/StarJson.cpp
@@ -24,7 +24,7 @@ Json::Type Json::typeFromName(String const& t) {
else if (t == "null")
return Type::Null;
else
- throw JsonException(strf("String '%s' is not a valid json type", t));
+ throw JsonException(strf("String '{}' is not a valid json type", t));
}
String Json::typeName(Type t) {
@@ -180,7 +180,7 @@ double Json::toDouble() const {
if (type() == Type::Int)
return (double)m_data.get<int64_t>();
- throw JsonException::format("Improper conversion to double from %s", typeName());
+ throw JsonException::format("Improper conversion to double from {}", typeName());
}
float Json::toFloat() const {
@@ -189,7 +189,7 @@ float Json::toFloat() const {
bool Json::toBool() const {
if (type() != Type::Bool)
- throw JsonException::format("Improper conversion to bool from %s", typeName());
+ throw JsonException::format("Improper conversion to bool from {}", typeName());
return m_data.get<bool>();
}
@@ -199,7 +199,7 @@ int64_t Json::toInt() const {
} else if (type() == Type::Int) {
return m_data.get<int64_t>();
} else {
- throw JsonException::format("Improper conversion to int from %s", typeName());
+ throw JsonException::format("Improper conversion to int from {}", typeName());
}
}
@@ -209,43 +209,43 @@ uint64_t Json::toUInt() const {
} else if (type() == Type::Int) {
return (uint64_t)m_data.get<int64_t>();
} else {
- throw JsonException::format("Improper conversion to unsigned int from %s", typeName());
+ throw JsonException::format("Improper conversion to unsigned int from {}", typeName());
}
}
String Json::toString() const {
if (type() != Type::String)
- throw JsonException(strf("Cannot convert from %s to string", typeName()));
+ throw JsonException(strf("Cannot convert from {} to string", typeName()));
return *m_data.get<StringConstPtr>();
}
JsonArray Json::toArray() const {
if (type() != Type::Array)
- throw JsonException::format("Improper conversion to JsonArray from %s", typeName());
+ throw JsonException::format("Improper conversion to JsonArray from {}", typeName());
return *m_data.get<JsonArrayConstPtr>();
}
JsonObject Json::toObject() const {
if (type() != Type::Object)
- throw JsonException::format("Improper conversion to JsonObject from %s", typeName());
+ throw JsonException::format("Improper conversion to JsonObject from {}", typeName());
return *m_data.get<JsonObjectConstPtr>();
}
StringConstPtr Json::stringPtr() const {
if (type() != Type::String)
- throw JsonException(strf("Cannot convert from %s to string", typeName()));
+ throw JsonException(strf("Cannot convert from {} to string", typeName()));
return m_data.get<StringConstPtr>();
}
JsonArrayConstPtr Json::arrayPtr() const {
if (type() != Type::Array)
- throw JsonException::format("Improper conversion to JsonArray from %s", typeName());
+ throw JsonException::format("Improper conversion to JsonArray from {}", typeName());
return m_data.get<JsonArrayConstPtr>();
}
JsonObjectConstPtr Json::objectPtr() const {
if (type() != Type::Object)
- throw JsonException::format("Improper conversion to JsonObject from %s", typeName());
+ throw JsonException::format("Improper conversion to JsonObject from {}", typeName());
return m_data.get<JsonObjectConstPtr>();
}
@@ -330,7 +330,7 @@ bool Json::contains(String const& key) const {
Json Json::get(size_t index) const {
if (auto p = ptr(index))
return *p;
- throw JsonException(strf("Json::get(%s) out of range", index));
+ throw JsonException(strf("Json::get({}) out of range", index));
}
double Json::getDouble(size_t index) const {
@@ -422,7 +422,7 @@ JsonObject Json::getObject(size_t index, JsonObject def) const {
Json Json::get(String const& key) const {
if (auto p = ptr(key))
return *p;
- throw JsonException(strf("No such key in Json::get(\"%s\")", key));
+ throw JsonException(strf("No such key in Json::get(\"{}\")", key));
}
double Json::getDouble(String const& key) const {
@@ -822,7 +822,7 @@ Json Json::convert(Type u) const {
case Type::Object:
return toObject();
default:
- throw JsonException::format("Improper conversion to type %s", typeName(u));
+ throw JsonException::format("Improper conversion to type {}", typeName(u));
}
}
@@ -997,7 +997,7 @@ size_t hash<Json>::operator()(Json const& v) const {
Json const* Json::ptr(size_t index) const {
if (type() != Type::Array)
- throw JsonException::format("Cannot call get with index on Json type %s, must be Array type", typeName());
+ throw JsonException::format("Cannot call get with index on Json type {}, must be Array type", typeName());
auto const& list = *m_data.get<JsonArrayConstPtr>();
if (index >= list.size())
@@ -1007,7 +1007,7 @@ Json const* Json::ptr(size_t index) const {
Json const* Json::ptr(String const& key) const {
if (type() != Type::Object)
- throw JsonException::format("Cannot call get with key on Json type %s, must be Object type", typeName());
+ throw JsonException::format("Cannot call get with key on Json type {}, must be Object type", typeName());
auto const& map = m_data.get<JsonObjectConstPtr>();
auto i = map->find(key);
diff --git a/source/core/StarJsonBuilder.cpp b/source/core/StarJsonBuilder.cpp
index 432cef9..6084c40 100644
--- a/source/core/StarJsonBuilder.cpp
+++ b/source/core/StarJsonBuilder.cpp
@@ -21,7 +21,7 @@ void JsonBuilderStream::endObject() {
Json v = pop();
String k = pop().toString();
if (!object.insert(k, move(v)).second)
- throw JsonParsingException(strf("Json object contains a duplicate entry for key '%s'", k));
+ throw JsonParsingException(strf("Json object contains a duplicate entry for key '{}'", k));
}
}
}
diff --git a/source/core/StarJsonBuilder.hpp b/source/core/StarJsonBuilder.hpp
index cd2d42d..6be9e54 100644
--- a/source/core/StarJsonBuilder.hpp
+++ b/source/core/StarJsonBuilder.hpp
@@ -62,9 +62,9 @@ Json inputUtf8Json(InputIterator begin, InputIterator end, bool fragment) {
Utf32Input pend = parser.parse(wbegin, wend, fragment);
if (parser.error())
- throw JsonParsingException(strf("Error parsing json: %s at %s:%s", parser.error(), parser.line(), parser.column()));
+ throw JsonParsingException(strf("Error parsing json: {} at {}:{}", parser.error(), parser.line(), parser.column()));
else if (pend != wend)
- throw JsonParsingException(strf("Error extra data at end of input at %s:%s", parser.line(), parser.column()));
+ throw JsonParsingException(strf("Error extra data at end of input at {}:{}", parser.line(), parser.column()));
return stream.takeTop();
}
@@ -85,9 +85,9 @@ Jsonlike inputUtf32Json(InputIterator begin, InputIterator end, bool fragment) {
InputIterator pend = parser.parse(begin, end, fragment);
if (parser.error()) {
- throw JsonParsingException(strf("Error parsing json: %s at %s:%s", parser.error(), parser.line(), parser.column()));
+ throw JsonParsingException(strf("Error parsing json: {} at {}:{}", parser.error(), parser.line(), parser.column()));
} else if (pend != end) {
- throw JsonParsingException(strf("Error extra data at end of input at %s:%s", parser.line(), parser.column()));
+ throw JsonParsingException(strf("Error extra data at end of input at {}:{}", parser.line(), parser.column()));
}
return stream.takeTop();
diff --git a/source/core/StarJsonExtra.cpp b/source/core/StarJsonExtra.cpp
index d683ca1..ec6fe90 100644
--- a/source/core/StarJsonExtra.cpp
+++ b/source/core/StarJsonExtra.cpp
@@ -147,7 +147,7 @@ RectD jsonToRectD(Json const& v) {
auto upperRight = jsonToVec2D(v.get(1));
return RectD(lowerLeft, upperRight);
} catch (JsonException const& e) {
- throw JsonException(strf("Inner position not well formed in jsonToRectD: %s", outputException(e, true)));
+ throw JsonException(strf("Inner position not well formed in jsonToRectD: {}", outputException(e, true)));
}
}
@@ -178,7 +178,7 @@ RectI jsonToRectI(Json const& v) {
auto upperRight = jsonToVec2I(v.get(1));
return RectI(lowerLeft, upperRight);
} catch (JsonException const& e) {
- throw JsonException(strf("Inner position not well formed in jsonToRectI: %s", outputException(e, true)));
+ throw JsonException(strf("Inner position not well formed in jsonToRectI: {}", outputException(e, true)));
}
}
@@ -201,7 +201,7 @@ RectU jsonToRectU(Json const& v) {
auto upperRight = jsonToVec2U(v.get(1));
return RectU(lowerLeft, upperRight);
} catch (JsonException const& e) {
- throw JsonException(strf("Inner position not well formed in jsonToRectU: %s", outputException(e, true)));
+ throw JsonException(strf("Inner position not well formed in jsonToRectU: {}", outputException(e, true)));
}
}
@@ -226,7 +226,7 @@ Color jsonToColor(Json const& v) {
} else if (v.type() == Json::Type::String) {
return Color(v.toString());
} else {
- throw JsonException(strf("Json of type %s cannot be converted to color", v.typeName()));
+ throw JsonException(strf("Json of type {} cannot be converted to color", v.typeName()));
}
}
diff --git a/source/core/StarJsonExtra.hpp b/source/core/StarJsonExtra.hpp
index cfe7efb..66d89d6 100644
--- a/source/core/StarJsonExtra.hpp
+++ b/source/core/StarJsonExtra.hpp
@@ -106,7 +106,7 @@ Json jsonFromWeightedPool(WeightedPool<T> const& pool, Converter&& converter);
template <size_t Size>
Array<unsigned, Size> jsonToArrayU(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToArrayU", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToArrayU", Size).c_str());
Array<unsigned, Size> res;
for (size_t i = 0; i < Size; i++) {
@@ -119,7 +119,7 @@ Array<unsigned, Size> jsonToArrayU(Json const& v) {
template <size_t Size>
Array<size_t, Size> jsonToArrayS(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToArrayS", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToArrayS", Size).c_str());
Array<size_t, Size> res;
for (size_t i = 0; i < Size; i++) {
@@ -132,7 +132,7 @@ Array<size_t, Size> jsonToArrayS(Json const& v) {
template <size_t Size>
Array<int, Size> jsonToArrayI(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToArrayI", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToArrayI", Size).c_str());
Array<int, Size> res;
for (size_t i = 0; i < Size; i++) {
@@ -145,7 +145,7 @@ Array<int, Size> jsonToArrayI(Json const& v) {
template <size_t Size>
Array<float, Size> jsonToArrayF(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToArrayF", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToArrayF", Size).c_str());
Array<float, Size> res;
for (size_t i = 0; i < Size; i++) {
@@ -158,7 +158,7 @@ Array<float, Size> jsonToArrayF(Json const& v) {
template <size_t Size>
Array<double, Size> jsonToArrayD(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToArrayD", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToArrayD", Size).c_str());
Array<double, Size> res;
for (size_t i = 0; i < Size; i++) {
@@ -171,7 +171,7 @@ Array<double, Size> jsonToArrayD(Json const& v) {
template <size_t Size>
Array<String, Size> jsonToStringArray(Json const& v) {
if (v.size() != Size)
- throw JsonException(strf("Json array not of size %d in jsonToStringArray", Size).c_str());
+ throw JsonException(strf("Json array not of size {} in jsonToStringArray", Size).c_str());
Array<String, Size> res;
for (size_t i = 0; i < Size; i++) {
diff --git a/source/core/StarJsonPatch.cpp b/source/core/StarJsonPatch.cpp
index e1ab6de..34c6a82 100644
--- a/source/core/StarJsonPatch.cpp
+++ b/source/core/StarJsonPatch.cpp
@@ -12,7 +12,7 @@ Json jsonPatch(Json const& base, JsonArray const& patch) {
}
return res;
} catch (JsonException const& e) {
- throw JsonPatchException(strf("Could not apply patch to base. %s", e.what()));
+ throw JsonPatchException(strf("Could not apply patch to base. {}", e.what()));
}
}
@@ -32,9 +32,9 @@ namespace JsonPatching {
auto operation = op.getString("op");
return JsonPatching::functionMap.get(operation)(base, op);
} catch (JsonException const& e) {
- throw JsonPatchException(strf("Could not apply operation to base. %s", e.what()));
+ throw JsonPatchException(strf("Could not apply operation to base. {}", e.what()));
} catch (MapException const&) {
- throw JsonPatchException(strf("Invalid operation: %s", op.getString("op")));
+ throw JsonPatchException(strf("Invalid operation: {}", op.getString("op")));
}
}
@@ -49,7 +49,7 @@ namespace JsonPatching {
auto testValue = pointer.get(base);
if (!value) {
if (inverseTest)
- throw JsonPatchTestFail(strf("Test operation failure, expected %s to be missing.", op.getString("path")));
+ throw JsonPatchTestFail(strf("Test operation failure, expected {} to be missing.", op.getString("path")));
return base;
}
@@ -57,11 +57,11 @@ namespace JsonPatching {
return base;
}
- throw JsonPatchTestFail(strf("Test operation failure, expected %s found %s.", value, testValue));
+ throw JsonPatchTestFail(strf("Test operation failure, expected {} found {}.", value, testValue));
} catch (JsonPath::TraversalException& e) {
if (inverseTest)
return base;
- throw JsonPatchTestFail(strf("Test operation failure: %s", e.what()));
+ throw JsonPatchTestFail(strf("Test operation failure: {}", e.what()));
}
}
diff --git a/source/core/StarJsonPath.cpp b/source/core/StarJsonPath.cpp
index 9eb5fae..c03e883 100644
--- a/source/core/StarJsonPath.cpp
+++ b/source/core/StarJsonPath.cpp
@@ -8,21 +8,21 @@ namespace JsonPath {
buffer.clear();
if (*iterator != '/')
- throw ParsingException::format("Missing leading '/' in Json pointer \"%s\"", path);
+ throw ParsingException::format("Missing leading '/' in Json pointer \"{}\"", path);
iterator++;
while (iterator != end && *iterator != '/') {
if (*iterator == '~') {
++iterator;
if (iterator == end)
- throw ParsingException::format("Incomplete escape sequence in Json pointer \"%s\"", path);
+ throw ParsingException::format("Incomplete escape sequence in Json pointer \"{}\"", path);
if (*iterator == '0')
buffer.append('~');
else if (*iterator == '1')
buffer.append('/');
else
- throw ParsingException::format("Invalid escape sequence in Json pointer \"%s\"", path);
+ throw ParsingException::format("Invalid escape sequence in Json pointer \"{}\"", path);
++iterator;
} else
buffer.append(*iterator++);
@@ -38,7 +38,7 @@ namespace JsonPath {
buffer.clear();
if (*iterator == '.') {
- throw ParsingException::format("Entry starts with '.' in query path \"%s\"", path);
+ throw ParsingException::format("Entry starts with '.' in query path \"{}\"", path);
} else if (*iterator == '[') {
// Parse array number and ']'
@@ -49,7 +49,7 @@ namespace JsonPath {
buffer.append(*iterator++);
if (iterator == end || *iterator != ']')
- throw ParsingException::format("Array has no trailing ']' or has invalid character in query path \"%s\"", path);
+ throw ParsingException::format("Array has no trailing ']' or has invalid character in query path \"{}\"", path);
// Consume trailing ']'
++iterator;
diff --git a/source/core/StarJsonPath.hpp b/source/core/StarJsonPath.hpp
index 0f0efa9..bd60dad 100644
--- a/source/core/StarJsonPath.hpp
+++ b/source/core/StarJsonPath.hpp
@@ -143,24 +143,24 @@ namespace JsonPath {
if (value.type() == Json::Type::Array) {
if (buffer == "-")
- throw TraversalException::format("Tried to get key '%s' in non-object type in pathGet(\"%s\")", buffer, path);
+ throw TraversalException::format("Tried to get key '{}' in non-object type in pathGet(\"{}\")", buffer, path);
Maybe<size_t> i = maybeLexicalCast<size_t>(buffer);
if (!i)
- throw TraversalException::format("Cannot parse '%s' as index in pathGet(\"%s\")", buffer, path);
+ throw TraversalException::format("Cannot parse '{}' as index in pathGet(\"{}\")", buffer, path);
if (*i < value.size())
value = value.get(*i);
else
- throw TraversalException::format("Index %s out of range in pathGet(\"%s\")", buffer, path);
+ throw TraversalException::format("Index {} out of range in pathGet(\"{}\")", buffer, path);
} else if (value.type() == Json::Type::Object) {
if (value.contains(buffer))
value = value.get(buffer);
else
- throw TraversalException::format("No such key '%s' in pathGet(\"%s\")", buffer, path);
+ throw TraversalException::format("No such key '{}' in pathGet(\"{}\")", buffer, path);
} else {
- throw TraversalException::format("Tried to get key '%s' in non-object type in pathGet(\"%s\")", buffer, path);
+ throw TraversalException::format("Tried to get key '{}' in non-object type in pathGet(\"{}\")", buffer, path);
}
}
return value;
@@ -218,10 +218,10 @@ namespace JsonPath {
} else {
Maybe<size_t> i = maybeLexicalCast<size_t>(buffer);
if (!i)
- throw TraversalException::format("Cannot parse '%s' as index in pathApply(\"%s\")", buffer, path);
+ throw TraversalException::format("Cannot parse '{}' as index in pathApply(\"{}\")", buffer, path);
if (*i >= value.size())
- throw TraversalException::format("Index %s out of range in pathApply(\"%s\")", buffer, path);
+ throw TraversalException::format("Index {} out of range in pathApply(\"{}\")", buffer, path);
return value.set(*i, pathApply(buffer, value.get(*i), parser, path, iterator, op));
}
@@ -232,7 +232,7 @@ namespace JsonPath {
} else {
if (!value.contains(buffer))
- throw TraversalException::format("No such key '%s' in pathApply(\"%s\")", buffer, path);
+ throw TraversalException::format("No such key '{}' in pathApply(\"{}\")", buffer, path);
Jsonlike newChild = pathApply(buffer, value.get(buffer), parser, path, iterator, op);
iterator = current;
@@ -242,7 +242,7 @@ namespace JsonPath {
}
} else {
- throw TraversalException::format("Tried to get key '%s' in non-object type in pathApply(\"%s\")", buffer, path);
+ throw TraversalException::format("Tried to get key '{}' in non-object type in pathApply(\"{}\")", buffer, path);
}
}
@@ -262,16 +262,16 @@ namespace JsonPath {
return arrayOp(parent, {});
Maybe<size_t> i = maybeLexicalCast<size_t>(*key);
if (!i)
- throw TraversalException::format("Cannot parse '%s' as index in Json path \"%s\"", *key, path);
+ throw TraversalException::format("Cannot parse '{}' as index in Json path \"{}\"", *key, path);
if (i && *i > parent.size())
- throw TraversalException::format("Index %s out of range in Json path \"%s\"", *key, path);
+ throw TraversalException::format("Index {} out of range in Json path \"{}\"", *key, path);
if (i && *i == parent.size())
i = {};
return arrayOp(parent, i);
} else if (parent.type() == Json::Type::Object) {
return objectOp(parent, *key);
} else {
- throw TraversalException::format("Tried to set key '%s' in non-object type in pathSet(\"%s\")", *key, path);
+ throw TraversalException::format("Tried to set key '{}' in non-object type in pathSet(\"{}\")", *key, path);
}
};
}
@@ -297,7 +297,7 @@ namespace JsonPath {
EmptyPathOp<Jsonlike> emptyPathOp = [](Jsonlike const&) { return Json{}; };
ObjectOp<Jsonlike> objectOp = [](Jsonlike const& object, String const& key) {
if (!object.contains(key))
- throw TraversalException::format("Could not find \"%s\" to remove", key);
+ throw TraversalException::format("Could not find \"{}\" to remove", key);
return object.eraseKey(key);
};
ArrayOp<Jsonlike> arrayOp = [](Jsonlike const& array, Maybe<size_t> i) {
diff --git a/source/core/StarJsonRpc.cpp b/source/core/StarJsonRpc.cpp
index 60779b9..f6def8f 100644
--- a/source/core/StarJsonRpc.cpp
+++ b/source/core/StarJsonRpc.cpp
@@ -12,7 +12,7 @@ JsonRpc::JsonRpc() {
void JsonRpc::registerHandler(String const& handler, JsonRpcRemoteFunction func) {
if (m_handlers.contains(handler))
- throw JsonRpcException(strf("Handler by that name already exists '%s'", handler));
+ throw JsonRpcException(strf("Handler by that name already exists '{}'", handler));
m_handlers.add(handler, move(func));
}
@@ -23,7 +23,7 @@ void JsonRpc::registerHandlers(JsonRpcHandlers const& handlers) {
void JsonRpc::removeHandler(String const& handler) {
if (!m_handlers.contains(handler))
- throw JsonRpcException(strf("No such handler by the name '%s'", handler));
+ throw JsonRpcException(strf("No such handler by the name '{}'", handler));
m_handlers.remove(handler);
}
@@ -76,14 +76,14 @@ void JsonRpc::receive(ByteArray const& inbuffer) {
try {
auto handlerName = request.getString("handler");
if (!m_handlers.contains(handlerName))
- throw JsonRpcException(strf("Unknown handler '%s'", handlerName));
+ throw JsonRpcException(strf("Unknown handler '{}'", handlerName));
m_pending.append(JsonObject{
{"command", "response"},
{"id", request.get("id")},
{"result", m_handlers[handlerName](request.get("arguments"))}
});
} catch (std::exception& e) {
- Logger::error("Exception while handling variant rpc request handler call. %s", outputException(e, false));
+ Logger::error("Exception while handling variant rpc request handler call. {}", outputException(e, false));
JsonObject response;
response["command"] = "fail";
response["id"] = request.get("id");
@@ -98,7 +98,7 @@ void JsonRpc::receive(ByteArray const& inbuffer) {
auto responseHandler = m_pendingResponse.take(request.getUInt("id"));
responseHandler.fulfill(request.get("result"));
} catch (std::exception& e) {
- Logger::error("Exception while handling variant rpc response handler call. %s", outputException(e, true));
+ Logger::error("Exception while handling variant rpc response handler call. {}", outputException(e, true));
}
} else if (request.get("command") == "fail") {
@@ -106,7 +106,7 @@ void JsonRpc::receive(ByteArray const& inbuffer) {
auto responseHandler = m_pendingResponse.take(request.getUInt("id"));
responseHandler.fulfill({});
} catch (std::exception& e) {
- Logger::error("Exception while handling variant rpc failure handler call. %s", outputException(e, true));
+ Logger::error("Exception while handling variant rpc failure handler call. {}", outputException(e, true));
}
}
}
diff --git a/source/core/StarLexicalCast.hpp b/source/core/StarLexicalCast.hpp
index 6359591..40e6d6d 100644
--- a/source/core/StarLexicalCast.hpp
+++ b/source/core/StarLexicalCast.hpp
@@ -39,7 +39,7 @@ Type lexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::bo
if (m)
return m.take();
else
- throw BadLexicalCast(strf("Lexical cast failed on '%s'", s));
+ throw BadLexicalCast(strf("Lexical cast failed on '{}'", s));
}
template <class Type>
diff --git a/source/core/StarList.hpp b/source/core/StarList.hpp
index e097721..49d2f84 100644
--- a/source/core/StarList.hpp
+++ b/source/core/StarList.hpp
@@ -668,14 +668,14 @@ size_t RandomAccessListMixin<BaseList>::lastIndexOf(const_reference e, size_t ti
template <typename BaseList>
auto RandomAccessListMixin<BaseList>::at(size_t n) const -> const_reference {
if (n >= Base::size())
- throw OutOfRangeException(strf("out of range list::at(%s)", n));
+ throw OutOfRangeException(strf("out of range list::at({})", n));
return operator[](n);
}
template <typename BaseList>
auto RandomAccessListMixin<BaseList>::at(size_t n) -> reference {
if (n >= Base::size())
- throw OutOfRangeException(strf("out of range list::at(%s)", n));
+ throw OutOfRangeException(strf("out of range list::at({})", n));
return operator[](n);
}
diff --git a/source/core/StarLockFile_unix.cpp b/source/core/StarLockFile_unix.cpp
index 9677f2d..298c636 100644
--- a/source/core/StarLockFile_unix.cpp
+++ b/source/core/StarLockFile_unix.cpp
@@ -39,7 +39,7 @@ bool LockFile::lock(int64_t timeout) {
auto doFLock = [](String const& filename, bool block) -> shared_ptr<int> {
int fd = open(filename.utf8Ptr(), O_RDONLY | O_CREAT, 0644);
if (fd < 0)
- throw StarException(strf("Could not open lock file %s, %s\n", filename, strerror(errno)));
+ throw StarException(strf("Could not open lock file {}, {}\n", filename, strerror(errno)));
int ret;
if (block)
@@ -50,7 +50,7 @@ bool LockFile::lock(int64_t timeout) {
if (ret != 0) {
close(fd);
if (errno != EWOULDBLOCK)
- throw StarException(strf("Could not lock file %s, %s\n", filename, strerror(errno)));
+ throw StarException(strf("Could not lock file {}, {}\n", filename, strerror(errno)));
return {};
}
diff --git a/source/core/StarLockFile_windows.cpp b/source/core/StarLockFile_windows.cpp
index 1cf1473..33692fb 100644
--- a/source/core/StarLockFile_windows.cpp
+++ b/source/core/StarLockFile_windows.cpp
@@ -41,7 +41,7 @@ bool LockFile::lock(int64_t timeout) {
if (handle == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_SHARING_VIOLATION)
return {};
- throw StarException(strf("Could not open lock file %s, error code %s\n", filename, GetLastError()));
+ throw StarException(strf("Could not open lock file {}, error code {}\n", filename, GetLastError()));
}
return make_shared<HANDLE>(handle);
diff --git a/source/core/StarLogging.cpp b/source/core/StarLogging.cpp
index 2a7f88e..55cd27d 100644
--- a/source/core/StarLogging.cpp
+++ b/source/core/StarLogging.cpp
@@ -24,7 +24,7 @@ LogLevel LogSink::level() {
void StdoutLogSink::log(char const* msg, LogLevel level) {
MutexLocker locker(m_logMutex);
- coutf("[%s] %s\n", LogLevelNames.getRight(level), msg);
+ coutf("[{}] {}\n", LogLevelNames.getRight(level), msg);
}
FileLogSink::FileLogSink(String const& filename, LogLevel level, bool truncate) {
@@ -37,7 +37,7 @@ FileLogSink::FileLogSink(String const& filename, LogLevel level, bool truncate)
void FileLogSink::log(char const* msg, LogLevel level) {
MutexLocker locker(m_logMutex);
- auto line = strf("[%s] [%s] %s\n", Time::printCurrentDateAndTime("<hours>:<minutes>:<seconds>.<millis>"), LogLevelNames.getRight(level), msg);
+ auto line = strf("[{}] [{}] {}\n", Time::printCurrentDateAndTime("<hours>:<minutes>:<seconds>.<millis>"), LogLevelNames.getRight(level), msg);
m_output->write(line.data(), line.size());
}
diff --git a/source/core/StarLogging.hpp b/source/core/StarLogging.hpp
index d90e0e1..ae47e40 100644
--- a/source/core/StarLogging.hpp
+++ b/source/core/StarLogging.hpp
@@ -185,7 +185,7 @@ void Logger::error(char const* msg, Args const&... args) {
template <typename T>
void LogMap::set(String const& key, T const& t) {
- setValue(key, strf("%s", t));
+ setValue(key, strf("{}", t));
}
}
diff --git a/source/core/StarLua.cpp b/source/core/StarLua.cpp
index 6034c06..eb8541c 100644
--- a/source/core/StarLua.cpp
+++ b/source/core/StarLua.cpp
@@ -65,7 +65,7 @@ LuaCallbacks& LuaCallbacks::merge(LuaCallbacks const& callbacks) {
for (auto const& pair : callbacks.m_callbacks)
m_callbacks.add(pair.first, pair.second);
} catch (MapException const& e) {
- throw LuaException(strf("Failed to merge LuaCallbacks: %s", outputException(e, true)));
+ throw LuaException(strf("Failed to merge LuaCallbacks: {}", outputException(e, true)));
}
return *this;
@@ -481,7 +481,7 @@ void LuaEngine::threadPushFunction(int threadIndex, int functionIndex) {
int status = lua_status(thread);
lua_Debug ar;
if (status != LUA_OK || lua_getstack(thread, 0, &ar) > 0 || lua_gettop(thread) > 0)
- throw LuaException(strf("Cannot push function to active or errored thread with status %s", status));
+ throw LuaException(strf("Cannot push function to active or errored thread with status {}", status));
pushHandle(thread, functionIndex);
}
@@ -633,9 +633,9 @@ void LuaEngine::handleError(lua_State* state, int res) {
String error;
if (lua_isstring(state, -1))
- error = strf("Error code %s, %s", res, lua_tostring(state, -1));
+ error = strf("Error code {}, {}", res, lua_tostring(state, -1));
else
- error = strf("Error code %s, <unknown error>", res);
+ error = strf("Error code {}, <unknown error>", res);
lua_pop(state, 1);
diff --git a/source/core/StarLua.hpp b/source/core/StarLua.hpp
index 95b4499..9241ec4 100644
--- a/source/core/StarLua.hpp
+++ b/source/core/StarLua.hpp
@@ -1717,20 +1717,20 @@ T& LuaUserData::get() const {
template <typename Function>
void LuaCallbacks::registerCallback(String name, Function&& func) {
if (!m_callbacks.insert(name, LuaDetail::wrapFunction(forward<Function>(func))).second)
- throw LuaException::format("Lua callback '%s' was registered twice", name);
+ throw LuaException::format("Lua callback '{}' was registered twice", name);
}
template <typename Return, typename... Args, typename Function>
void LuaCallbacks::registerCallbackWithSignature(String name, Function&& func) {
if (!m_callbacks.insert(name, LuaDetail::wrapFunctionWithSignature<Return, Args...>(forward<Function>(func))).second)
- throw LuaException::format("Lua callback '%s' was registered twice", name);
+ throw LuaException::format("Lua callback '{}' was registered twice", name);
}
template <typename T>
template <typename Function>
void LuaMethods<T>::registerMethod(String name, Function&& func) {
if (!m_methods.insert(name, LuaDetail::wrapMethod(forward<Function>(move(func)))).second)
- throw LuaException::format("Lua method '%s' was registered twice", name);
+ throw LuaException::format("Lua method '{}' was registered twice", name);
}
template <typename T>
@@ -1738,7 +1738,7 @@ template <typename Return, typename... Args, typename Function>
void LuaMethods<T>::registerMethodWithSignature(String name, Function&& func) {
if (!m_methods.insert(name, LuaDetail::wrapMethodWithSignature<Return, Args...>(forward<Function>(move(func))))
.second)
- throw LuaException::format("Lua method '%s' was registered twice", name);
+ throw LuaException::format("Lua method '{}' was registered twice", name);
}
template <typename T>
@@ -1766,7 +1766,7 @@ Ret LuaContext::invokePath(String const& key, Args const&... args) const {
auto p = getPath(key);
if (auto f = p.ptr<LuaFunction>())
return f->invoke<Ret>(args...);
- throw LuaException::format("invokePath called on path '%s' which is not function type", key);
+ throw LuaException::format("invokePath called on path '{}' which is not function type", key);
}
template <typename T>
@@ -1867,14 +1867,14 @@ template <typename T>
T LuaEngine::luaTo(LuaValue&& v) {
if (auto res = luaMaybeTo<T>(move(v)))
return res.take();
- throw LuaConversionException::format("Error converting LuaValue to type '%s'", typeid(T).name());
+ throw LuaConversionException::format("Error converting LuaValue to type '{}'", typeid(T).name());
}
template <typename T>
T LuaEngine::luaTo(LuaValue const& v) {
if (auto res = luaMaybeTo<T>(v))
return res.take();
- throw LuaConversionException::format("Error converting LuaValue to type '%s'", typeid(T).name());
+ throw LuaConversionException::format("Error converting LuaValue to type '{}'", typeid(T).name());
}
template <typename Container>
@@ -2089,7 +2089,7 @@ template <typename T>
T* LuaEngine::getUserData(int handleIndex) {
int typeRef = m_registeredUserDataTypes.value(typeid(T), LUA_NOREF);
if (typeRef == LUA_NOREF)
- throw LuaException::format("Cannot convert userdata type of %s, not registered", typeid(T).name());
+ throw LuaException::format("Cannot convert userdata type of {}, not registered", typeid(T).name());
lua_checkstack(m_state, 3);
@@ -2103,7 +2103,7 @@ T* LuaEngine::getUserData(int handleIndex) {
lua_rawgeti(m_state, LUA_REGISTRYINDEX, typeRef);
if (!lua_rawequal(m_state, -1, -2)) {
lua_pop(m_state, 3);
- throw LuaException::format("Improper conversion from userdata to type %s", typeid(T).name());
+ throw LuaException::format("Improper conversion from userdata to type {}", typeid(T).name());
}
lua_pop(m_state, 3);
diff --git a/source/core/StarMap.hpp b/source/core/StarMap.hpp
index e4941f3..cf9c260 100644
--- a/source/core/StarMap.hpp
+++ b/source/core/StarMap.hpp
@@ -163,7 +163,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::take(key_type const& k) -> mapped_type {
if (auto v = maybeTake(k))
return v.take();
- throw MapException(strf("Key '%s' not found in Map::take()", outputAny(k)));
+ throw MapException(strf("Key '{}' not found in Map::take()", outputAny(k)));
}
template <typename BaseMap>
@@ -182,7 +182,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::get(key_type const& k) -> mapped_type& {
iterator i = Base::find(k);
if (i == Base::end())
- throw MapException(strf("Key '%s' not found in Map::get()", outputAny(k)));
+ throw MapException(strf("Key '{}' not found in Map::get()", outputAny(k)));
return i->second;
}
@@ -190,7 +190,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::get(key_type const& k) const -> mapped_type const& {
const_iterator i = Base::find(k);
if (i == Base::end())
- throw MapException(strf("Key '%s' not found in Map::get()", outputAny(k)));
+ throw MapException(strf("Key '{}' not found in Map::get()", outputAny(k)));
return i->second;
}
@@ -236,7 +236,7 @@ auto MapMixin<BaseMap>::keyOf(mapped_type const& v) const -> key_type {
if (i->second == v)
return i->first;
}
- throw MapException(strf("Value '%s' not found in Map::keyOf()", outputAny(v)));
+ throw MapException(strf("Value '{}' not found in Map::keyOf()", outputAny(v)));
}
template <typename BaseMap>
@@ -267,7 +267,7 @@ template <typename BaseMap>
auto MapMixin<BaseMap>::add(key_type k, mapped_type v) -> mapped_type& {
auto pair = Base::insert(value_type(move(k), move(v)));
if (!pair.second)
- throw MapException(strf("Entry with key '%s' already present.", outputAny(k)));
+ throw MapException(strf("Entry with key '{}' already present.", outputAny(k)));
else
return pair.first->second;
}
diff --git a/source/core/StarMultiArray.hpp b/source/core/StarMultiArray.hpp
index f2cf155..3668c8a 100644
--- a/source/core/StarMultiArray.hpp
+++ b/source/core/StarMultiArray.hpp
@@ -291,7 +291,7 @@ template <typename Element, size_t Rank>
Element const& MultiArray<Element, Rank>::at(IndexArray const& index) const {
for (size_t i = Rank; i != 0; --i) {
if (index[i - 1] >= m_shape[i - 1])
- throw MultiArrayException(strf("Out of bounds on MultiArray::at(%s)", index));
+ throw MultiArrayException(strf("Out of bounds on MultiArray::at({})", index));
}
return m_data[storageIndex(index)];
@@ -301,7 +301,7 @@ template <typename Element, size_t Rank>
Element& MultiArray<Element, Rank>::at(IndexArray const& index) {
for (size_t i = Rank; i != 0; --i) {
if (index[i - 1] >= m_shape[i - 1])
- throw MultiArrayException(strf("Out of bounds on MultiArray::at(%s)", index));
+ throw MultiArrayException(strf("Out of bounds on MultiArray::at({})", index));
}
return m_data[storageIndex(index)];
@@ -323,7 +323,7 @@ template <typename Element, size_t Rank>
void MultiArray<Element, Rank>::set(IndexArray const& index, Element element) {
for (size_t i = Rank; i != 0; --i) {
if (index[i - 1] >= m_shape[i - 1])
- throw MultiArrayException(strf("Out of bounds on MultiArray::set(%s)", index));
+ throw MultiArrayException(strf("Out of bounds on MultiArray::set({})", index));
}
m_data[storageIndex(index)] = move(element);
diff --git a/source/core/StarNetElementContainers.hpp b/source/core/StarNetElementContainers.hpp
index 5c2fd71..2127076 100644
--- a/source/core/StarNetElementContainers.hpp
+++ b/source/core/StarNetElementContainers.hpp
@@ -266,7 +266,7 @@ auto NetElementMapWrapper<BaseMap>::insert(key_type k, mapped_type v) -> pair<co
template <typename BaseMap>
void NetElementMapWrapper<BaseMap>::add(key_type k, mapped_type v) {
if (!insert(value_type(move(k), move(v))).second)
- throw MapException::format("Entry with key '%s' already present.", outputAny(k));
+ throw MapException::format("Entry with key '{}' already present.", outputAny(k));
}
template <typename BaseMap>
@@ -321,7 +321,7 @@ template <typename BaseMap>
auto NetElementMapWrapper<BaseMap>::take(key_type const& k) -> mapped_type {
auto i = BaseMap::find(k);
if (i == BaseMap::end())
- throw MapException::format("Key '%s' not found in Map::take()", outputAny(k));
+ throw MapException::format("Key '{}' not found in Map::take()", outputAny(k));
auto m = move(i->second);
erase(i);
return m;
diff --git a/source/core/StarNetImpl.hpp b/source/core/StarNetImpl.hpp
index 80d75da..076b181 100644
--- a/source/core/StarNetImpl.hpp
+++ b/source/core/StarNetImpl.hpp
@@ -57,7 +57,7 @@ inline String netErrorString() {
return result;
#else
- return strf("%s - %s", errno, strerror(errno));
+ return strf("{} - {}", errno, strerror(errno));
#endif
}
@@ -144,7 +144,7 @@ struct SocketImpl {
int ret = ::setsockopt(socketDesc, level, optname, optval, len);
#endif
if (ret < 0)
- throw NetworkException(strf("setSockOpt failed to set %d, %d: %s", level, optname, netErrorString()));
+ throw NetworkException(strf("setSockOpt failed to set {}, {}: {}", level, optname, netErrorString()));
}
#ifdef STAR_SYSTEM_FAMILY_WINDOWS
diff --git a/source/core/StarOptionParser.cpp b/source/core/StarOptionParser.cpp
index ecf6e28..f849f43 100644
--- a/source/core/StarOptionParser.cpp
+++ b/source/core/StarOptionParser.cpp
@@ -17,12 +17,12 @@ void OptionParser::setAdditionalHelp(String help) {
void OptionParser::addSwitch(String const& flag, String description) {
if (!m_options.insert(flag, Switch{flag, move(description)}).second)
- throw OptionParserException::format("Duplicate switch '-%s' added", flag);
+ throw OptionParserException::format("Duplicate switch '-{}' added", flag);
}
void OptionParser::addParameter(String const& flag, String argument, RequirementMode requirementMode, String description) {
if (!m_options.insert(flag, Parameter{flag, move(argument), requirementMode, move(description)}).second)
- throw OptionParserException::format("Duplicate flag '-%s' added", flag);
+ throw OptionParserException::format("Duplicate flag '-{}' added", flag);
}
void OptionParser::addArgument(String argument, RequirementMode requirementMode, String description) {
@@ -46,7 +46,7 @@ pair<OptionParser::Options, StringList> OptionParser::parseOptions(StringList co
String flag = arg.substr(1);
auto option = m_options.maybe(flag);
if (!option) {
- errors.append(strf("No such option '-%s'", flag));
+ errors.append(strf("No such option '-{}'", flag));
continue;
}
@@ -55,12 +55,12 @@ pair<OptionParser::Options, StringList> OptionParser::parseOptions(StringList co
} else {
auto const& parameter = option->get<Parameter>();
if (!it.hasNext()) {
- errors.append(strf("Option '-%s' must be followed by an argument", flag));
+ errors.append(strf("Option '-{}' must be followed by an argument", flag));
continue;
}
String val = it.next();
if (parameter.requirementMode != Multiple && result.parameters.contains(flag)) {
- errors.append(strf("Option with argument '-%s' specified multiple times", flag));
+ errors.append(strf("Option with argument '-{}' specified multiple times", flag));
continue;
}
result.parameters[move(flag)].append(move(val));
@@ -75,7 +75,7 @@ pair<OptionParser::Options, StringList> OptionParser::parseOptions(StringList co
if (pair.second.is<Parameter>()) {
auto const& na = pair.second.get<Parameter>();
if (na.requirementMode == Required && !result.parameters.contains(pair.first))
- errors.append(strf("Missing required flag with argument '-%s'", pair.first));
+ errors.append(strf("Missing required flag with argument '-{}'", pair.first));
}
}
@@ -91,72 +91,72 @@ pair<OptionParser::Options, StringList> OptionParser::parseOptions(StringList co
}
if (result.arguments.size() < minimumArguments)
errors.append(strf(
- "Too few positional arguments given, expected at least %s got %s", minimumArguments, result.arguments.size()));
+ "Too few positional arguments given, expected at least {} got {}", minimumArguments, result.arguments.size()));
if (result.arguments.size() > maximumArguments)
errors.append(strf(
- "Too many positional arguments given, expected at most %s got %s", maximumArguments, result.arguments.size()));
+ "Too many positional arguments given, expected at most {} got {}", maximumArguments, result.arguments.size()));
return {move(result), move(errors)};
}
void OptionParser::printHelp(std::ostream& os) const {
if (!m_commandName.empty() && !m_summary.empty())
- format(os, "%s: %s\n\n", m_commandName, m_summary);
+ format(os, "{}: {}\n\n", m_commandName, m_summary);
else if (!m_commandName.empty())
- format(os, "%s:\n\n", m_commandName);
+ format(os, "{}:\n\n", m_commandName);
else if (!m_summary.empty())
- format(os, "%s\n\n", m_summary);
+ format(os, "{}\n\n", m_summary);
String cmdLineText;
for (auto const& p : m_options) {
if (p.second.is<Switch>()) {
- cmdLineText += strf(" [-%s]", p.first);
+ cmdLineText += strf(" [-{}]", p.first);
} else {
auto const& parameter = p.second.get<Parameter>();
if (parameter.requirementMode == Optional)
- cmdLineText += strf(" [-%s <%s>]", parameter.flag, parameter.argument);
+ cmdLineText += strf(" [-{} <{}>]", parameter.flag, parameter.argument);
else if (parameter.requirementMode == Required)
- cmdLineText += strf(" -%s <%s>", parameter.flag, parameter.argument);
+ cmdLineText += strf(" -{} <{}>", parameter.flag, parameter.argument);
else if (parameter.requirementMode == Multiple)
- cmdLineText += strf(" [-%s <%s>]...", parameter.flag, parameter.argument);
+ cmdLineText += strf(" [-{} <{}>]...", parameter.flag, parameter.argument);
}
}
for (auto const& p : m_arguments) {
if (p.requirementMode == Optional)
- cmdLineText += strf(" [<%s>]", p.argumentName);
+ cmdLineText += strf(" [<{}>]", p.argumentName);
else if (p.requirementMode == Required)
- cmdLineText += strf(" <%s>", p.argumentName);
+ cmdLineText += strf(" <{}>", p.argumentName);
else
- cmdLineText += strf(" [<%s>...]", p.argumentName);
+ cmdLineText += strf(" [<{}>...]", p.argumentName);
}
if (m_commandName.empty())
- format(os, "Command Line Usage:%s\n", cmdLineText);
+ format(os, "Command Line Usage:{}\n", cmdLineText);
else
- format(os, "Command Line Usage: %s%s\n", m_commandName, cmdLineText);
+ format(os, "Command Line Usage: {}{}\n", m_commandName, cmdLineText);
for (auto const& p : m_options) {
if (p.second.is<Switch>()) {
auto const& sw = p.second.get<Switch>();
if (!sw.description.empty())
- format(os, " -%s\t- %s\n", sw.flag, sw.description);
+ format(os, " -{}\t- {}\n", sw.flag, sw.description);
}
if (p.second.is<Parameter>()) {
auto const& parameter = p.second.get<Parameter>();
if (!parameter.description.empty())
- format(os, " -%s <%s>\t- %s\n", parameter.flag, parameter.argument, parameter.description);
+ format(os, " -{} <{}>\t- {}\n", parameter.flag, parameter.argument, parameter.description);
}
}
for (auto const& p : m_arguments) {
if (!p.description.empty())
- format(os, " <%s>\t- %s\n", p.argumentName, p.description);
+ format(os, " <{}>\t- {}\n", p.argumentName, p.description);
}
if (!m_additionalHelp.empty())
- format(os, "\n%s\n", m_additionalHelp);
+ format(os, "\n{}\n", m_additionalHelp);
}
}
diff --git a/source/core/StarOrderedMap.hpp b/source/core/StarOrderedMap.hpp
index 71fe816..4f2dc22 100644
--- a/source/core/StarOrderedMap.hpp
+++ b/source/core/StarOrderedMap.hpp
@@ -228,7 +228,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::get(key_type const& k) -> mapped_type& {
auto i = m_map.find(k);
if (i == m_map.end())
- throw MapException(strf("Key '%s' not found in OrderedMap::get()", outputAny(k)));
+ throw MapException(strf("Key '{}' not found in OrderedMap::get()", outputAny(k)));
return i->second->second;
}
@@ -308,7 +308,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::keyOf(mapped_typ
if (i->second == v)
return i->first;
}
- throw MapException(strf("Value '%s' not found in OrderedMap::keyOf()", outputAny(v)));
+ throw MapException(strf("Value '{}' not found in OrderedMap::keyOf()", outputAny(v)));
}
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
@@ -359,7 +359,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::add(key_type k, mapped_type v) -> mapped_type& {
auto pair = insert(value_type(move(k), move(v)));
if (!pair.second)
- throw MapException(strf("Entry with key '%s' already present.", outputAny(k)));
+ throw MapException(strf("Entry with key '{}' already present.", outputAny(k)));
else
return pair.first->second;
}
@@ -405,7 +405,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::take(key_type co
m_order.erase(i->second);
return v;
} else {
- throw MapException(strf("Key '%s' not found in OrderedMap::take()", outputAny(k)));
+ throw MapException(strf("Key '{}' not found in OrderedMap::take()", outputAny(k)));
}
}
@@ -509,7 +509,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::indexOf(key_type
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::keyAt(size_t i) const -> key_type const& {
if (i >= size())
- throw MapException(strf("index %s out of range in OrderedMap::at()", i));
+ throw MapException(strf("index {} out of range in OrderedMap::at()", i));
auto it = begin();
std::advance(it, i);
@@ -524,7 +524,7 @@ auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::valueAt(size_t i
template <template <typename...> class Map, typename Key, typename Value, typename Allocator, typename... MapArgs>
auto OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::valueAt(size_t i) -> mapped_type& {
if (i >= size())
- throw MapException(strf("index %s out of range in OrderedMap::valueAt()", i));
+ throw MapException(strf("index {} out of range in OrderedMap::valueAt()", i));
auto it = m_order.begin();
std::advance(it, i);
@@ -612,7 +612,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
void OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::toBack(key_type const& k) {
auto i = m_map.find(k);
if (i == m_map.end())
- throw MapException(strf("Key not found in OrderedMap::toBack('%s')", outputAny(k)));
+ throw MapException(strf("Key not found in OrderedMap::toBack('{}')", outputAny(k)));
toBack(i->second);
}
@@ -621,7 +621,7 @@ template <template <typename...> class Map, typename Key, typename Value, typena
void OrderedMapWrapper<Map, Key, Value, Allocator, MapArgs...>::toFront(key_type const& k) {
auto i = m_map.find(k);
if (i == m_map.end())
- throw MapException(strf("Key not found in OrderedMap::toFront('%s')", outputAny(k)));
+ throw MapException(strf("Key not found in OrderedMap::toFront('{}')", outputAny(k)));
toFront(i->second);
}
diff --git a/source/core/StarSignalHandler_windows.cpp b/source/core/StarSignalHandler_windows.cpp
index 0445aba..29e93c5 100644
--- a/source/core/StarSignalHandler_windows.cpp
+++ b/source/core/StarSignalHandler_windows.cpp
@@ -59,19 +59,19 @@ struct SignalHandlerImpl {
else if (modeFlag == 8)
mode = "Execute";
else
- mode = strf("Mode(%s)", modeFlag);
- g_sehMessage = strf("Access violation detected at %s (%s of address %s)",
+ mode = strf("Mode({})", modeFlag);
+ g_sehMessage = strf("Access violation detected at {} ({} of address {})",
ExceptionInfo->ExceptionRecord->ExceptionAddress,
mode,
(PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
} else {
g_sehMessage = msg;
- g_sehMessage = strf("%s (%p @ %s)",
+ g_sehMessage = strf("{} (%p @ {})",
g_sehMessage,
ExceptionInfo->ExceptionRecord->ExceptionCode,
ExceptionInfo->ExceptionRecord->ExceptionAddress);
for (DWORD i = 0; i < ExceptionInfo->ExceptionRecord->NumberParameters; i++)
- g_sehMessage = strf("%s [%s]", g_sehMessage, (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[i]);
+ g_sehMessage = strf("{} [{}]", g_sehMessage, (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[i]);
}
// setup a hijack into our own trampoline as if the failure actually was a
diff --git a/source/core/StarSmallVector.hpp b/source/core/StarSmallVector.hpp
index 38d32a3..2a77a3d 100644
--- a/source/core/StarSmallVector.hpp
+++ b/source/core/StarSmallVector.hpp
@@ -209,7 +209,7 @@ void SmallVector<Element, MaxStackSize>::reserve(size_t newCapacity) {
newCapacity = max(oldCapacity * 2, newCapacity);
auto newMem = (Element*)Star::malloc(newCapacity * sizeof(Element));
if (!newMem)
- throw MemoryException::format("Could not set new SmallVector capacity %s\n", newCapacity);
+ throw MemoryException::format("Could not set new SmallVector capacity {}\n", newCapacity);
size_t size = m_end - m_begin;
auto oldMem = m_begin;
@@ -238,14 +238,14 @@ void SmallVector<Element, MaxStackSize>::reserve(size_t newCapacity) {
template <typename Element, size_t MaxStackSize>
auto SmallVector<Element, MaxStackSize>::at(size_t i) -> reference {
if (i >= size())
- throw OutOfRangeException::format("out of range in SmallVector::at(%s)", i);
+ throw OutOfRangeException::format("out of range in SmallVector::at({})", i);
return m_begin[i];
}
template <typename Element, size_t MaxStackSize>
auto SmallVector<Element, MaxStackSize>::at(size_t i) const -> const_reference {
if (i >= size())
- throw OutOfRangeException::format("out of range in SmallVector::at(%s)", i);
+ throw OutOfRangeException::format("out of range in SmallVector::at({})", i);
return m_begin[i];
}
diff --git a/source/core/StarSocket.cpp b/source/core/StarSocket.cpp
index 95ffe7c..9b866b8 100644
--- a/source/core/StarSocket.cpp
+++ b/source/core/StarSocket.cpp
@@ -49,7 +49,7 @@ Maybe<SocketPollResult> Socket::poll(SocketPollQuery const& query, unsigned time
ret = ::select(0, &readfs, &writefs, &exceptfs, &time);
if (ret < 0)
- throw NetworkException::format("Error during call to select, '%s'", netErrorString());
+ throw NetworkException::format("Error during call to select, '{}'", netErrorString());
if (ret == 0)
return {};
@@ -82,7 +82,7 @@ Maybe<SocketPollResult> Socket::poll(SocketPollQuery const& query, unsigned time
ret = ::poll(pollfds.get(), query.size(), timeout);
if (ret < 0)
- throw NetworkException::format("Error during call to poll, '%s'", netErrorString());
+ throw NetworkException::format("Error during call to poll, '{}'", netErrorString());
if (ret == 0)
return {};
@@ -127,18 +127,18 @@ void Socket::bind(HostAddressWithPort const& addressWithPort) {
m_localAddress = addressWithPort;
setNativeFromAddress(m_localAddress, &sockAddr, &sockAddrLen);
if (::bind(m_impl->socketDesc, (struct sockaddr*)&sockAddr, sockAddrLen) < 0)
- throw NetworkException(strf("Cannot bind socket to %s: %s", m_localAddress, netErrorString()));
+ throw NetworkException(strf("Cannot bind socket to {}: {}", m_localAddress, netErrorString()));
m_socketMode = SocketMode::Bound;
- Logger::debug("bind %s (%d)", addressWithPort, m_impl->socketDesc);
+ Logger::debug("bind {} ({})", addressWithPort, m_impl->socketDesc);
}
void Socket::listen(int backlog) {
WriteLocker locker(m_mutex);
if (::listen(m_impl->socketDesc, backlog) != 0)
- throw NetworkException(strf("Could not listen on socket: '%s'", netErrorString()));
+ throw NetworkException(strf("Could not listen on socket: '{}'", netErrorString()));
}
void Socket::setTimeout(unsigned timeout) {
@@ -168,14 +168,14 @@ void Socket::setNonBlocking(bool nonBlocking) {
#ifdef WIN32
unsigned long mode = nonBlocking ? 1 : 0;
if (ioctlsocket(m_impl->socketDesc, FIONBIO, &mode) != 0)
- throw NetworkException::format("Cannot set socket non-blocking mode: %s", netErrorString());
+ throw NetworkException::format("Cannot set socket non-blocking mode: {}", netErrorString());
#else
int flags = fcntl(m_impl->socketDesc, F_GETFL, 0);
if (flags < 0)
- throw NetworkException::format("fcntl failure getting socket flags: %s", netErrorString());
+ throw NetworkException::format("fcntl failure getting socket flags: {}", netErrorString());
flags = nonBlocking ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
if (fcntl(m_impl->socketDesc, F_SETFL, flags) != 0)
- throw NetworkException::format("fcntl failure setting non-blocking mode: %s", netErrorString());
+ throw NetworkException::format("fcntl failure setting non-blocking mode: {}", netErrorString());
#endif
}
@@ -216,7 +216,7 @@ Socket::Socket(SocketType type, NetworkMode networkMode)
m_impl->socketDesc = ::socket(AF_INET6, type == SocketType::Tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
if (invalidSocketDescriptor(m_impl->socketDesc))
- throw NetworkException(strf("cannot create socket: %s", netErrorString()));
+ throw NetworkException(strf("cannot create socket: {}", netErrorString()));
m_socketMode = SocketMode::Shutdown;
setTimeout(60000);
@@ -231,7 +231,7 @@ Socket::Socket(NetworkMode networkMode, SocketImplPtr impl, SocketMode socketMod
void Socket::checkOpen(char const* methodName) const {
if (m_socketMode == SocketMode::Closed)
- throw SocketClosedException::format("Socket not open in %s", methodName);
+ throw SocketClosedException::format("Socket not open in {}", methodName);
}
void Socket::doShutdown() {
diff --git a/source/core/StarStaticVector.hpp b/source/core/StarStaticVector.hpp
index 693dc10..3a4a7cc 100644
--- a/source/core/StarStaticVector.hpp
+++ b/source/core/StarStaticVector.hpp
@@ -188,7 +188,7 @@ bool StaticVector<Element, MaxSize>::empty() const {
template <typename Element, size_t MaxSize>
void StaticVector<Element, MaxSize>::resize(size_t size, Element const& e) {
if (size > MaxSize)
- throw StaticVectorSizeException::format("StaticVector::resize(%s) out of range %s", m_size + size, MaxSize);
+ throw StaticVectorSizeException::format("StaticVector::resize({}) out of range {}", m_size + size, MaxSize);
for (size_t i = m_size; i > size; --i)
pop_back();
@@ -199,14 +199,14 @@ void StaticVector<Element, MaxSize>::resize(size_t size, Element const& e) {
template <typename Element, size_t MaxSize>
auto StaticVector<Element, MaxSize>::at(size_t i) -> reference {
if (i >= m_size)
- throw OutOfRangeException::format("out of range in StaticVector::at(%s)", i);
+ throw OutOfRangeException::format("out of range in StaticVector::at({})", i);
return ptr()[i];
}
template <typename Element, size_t MaxSize>
auto StaticVector<Element, MaxSize>::at(size_t i) const -> const_reference {
if (i >= m_size)
- throw OutOfRangeException::format("out of range in StaticVector::at(%s)", i);
+ throw OutOfRangeException::format("out of range in StaticVector::at({})", i);
return ptr()[i];
}
@@ -329,7 +329,7 @@ template <typename Element, size_t MaxSize>
template <typename... Args>
void StaticVector<Element, MaxSize>::emplace_back(Args&&... args) {
if (m_size + 1 > MaxSize)
- throw StaticVectorSizeException::format("StaticVector::emplace_back would extend StaticVector beyond size %s", MaxSize);
+ throw StaticVectorSizeException::format("StaticVector::emplace_back would extend StaticVector beyond size {}", MaxSize);
m_size += 1;
new (ptr() + m_size - 1) Element(forward<Args>(args)...);
diff --git a/source/core/StarString.cpp b/source/core/StarString.cpp
index aae3410..924c83b 100644
--- a/source/core/StarString.cpp
+++ b/source/core/StarString.cpp
@@ -187,7 +187,7 @@ bool CaseInsensitiveStringCompare::operator()(String const& lhs, String const& r
String::Char String::at(size_t i) const {
if (i > size())
- throw OutOfRangeException(strf("Out of range in String::at(%s)", i));
+ throw OutOfRangeException(strf("Out of range in String::at({})", i));
return operator[](i);
}
@@ -744,7 +744,7 @@ bool String::equalsIgnoreCase(String const& s) const {
String String::substr(size_t position, size_t n) const {
auto len = size();
if (position > len)
- throw OutOfRangeException(strf("out of range in String::substr(%s, %s)", position, n));
+ throw OutOfRangeException(strf("out of range in String::substr({}, {})", position, n));
if (position == 0 && n >= len)
return *this;
diff --git a/source/core/StarString.hpp b/source/core/StarString.hpp
index 7bca996..a401076 100644
--- a/source/core/StarString.hpp
+++ b/source/core/StarString.hpp
@@ -388,7 +388,7 @@ String String::lookupTags(Lookup&& lookup) const {
auto substrInto = [](std::string const& ref, size_t position, size_t n, std::string& result) {
auto len = ref.size();
if (position > len)
- throw OutOfRangeException(strf("out of range in substrInto: %s", position));
+ throw OutOfRangeException(strf("out of range in substrInto: {}", position));
auto it = ref.begin();
std::advance(it, position);
diff --git a/source/core/StarStringView.cpp b/source/core/StarStringView.cpp
index 7580bf6..36ad9b2 100644
--- a/source/core/StarStringView.cpp
+++ b/source/core/StarStringView.cpp
@@ -78,7 +78,7 @@ StringView::Char StringView::operator[](size_t index) const {
StringView::Char StringView::at(size_t i) const {
if (i > size())
- throw OutOfRangeException(strf("Out of range in StringView::at(%s)", i));
+ throw OutOfRangeException(strf("Out of range in StringView::at({})", i));
return operator[](i);
}
@@ -340,7 +340,7 @@ bool StringView::equalsIgnoreCase(StringView s) const {
StringView StringView::substr(size_t position, size_t n) const {
auto len = size();
if (position > len)
- throw OutOfRangeException(strf("out of range in StringView::substr(%s, %s)", position, n));
+ throw OutOfRangeException(strf("out of range in StringView::substr({}, {})", position, n));
if (position == 0 && n >= len)
return *this;
diff --git a/source/core/StarTcp.cpp b/source/core/StarTcp.cpp
index dc64b98..04a74f0 100644
--- a/source/core/StarTcp.cpp
+++ b/source/core/StarTcp.cpp
@@ -31,7 +31,7 @@ TcpSocketPtr TcpSocket::accept() {
if (invalidSocketDescriptor(socketDesc)) {
if (netErrorInterrupt())
return {};
- throw NetworkException(strf("Cannot accept connection: %s", netErrorString()));
+ throw NetworkException(strf("Cannot accept connection: {}", netErrorString()));
}
auto socketImpl = make_shared<SocketImpl>();
@@ -47,7 +47,7 @@ TcpSocketPtr TcpSocket::accept() {
sockPtr->m_localAddress = m_localAddress;
setAddressFromNative(sockPtr->m_remoteAddress, m_localAddress.address().mode(), &sockAddr);
- Logger::debug("accept from %s (%d)", sockPtr->m_remoteAddress, sockPtr->m_impl->socketDesc);
+ Logger::debug("accept from {} ({})", sockPtr->m_remoteAddress, sockPtr->m_impl->socketDesc);
return sockPtr;
}
@@ -83,7 +83,7 @@ size_t TcpSocket::receive(char* data, size_t size) {
} else if (netErrorInterrupt()) {
r = 0;
} else {
- throw NetworkException(strf("tcp recv error: %s", netErrorString()));
+ throw NetworkException(strf("tcp recv error: {}", netErrorString()));
}
}
@@ -113,7 +113,7 @@ size_t TcpSocket::send(char const* data, size_t size) {
} else if (netErrorInterrupt()) {
w = 0;
} else {
- throw NetworkException(strf("tcp send error: %s", netErrorString()));
+ throw NetworkException(strf("tcp send error: {}", netErrorString()));
}
}
@@ -145,7 +145,7 @@ void TcpSocket::connect(HostAddressWithPort const& addressWithPort) {
socklen_t sockAddrLen;
setNativeFromAddress(addressWithPort, &sockAddr, &sockAddrLen);
if (::connect(m_impl->socketDesc, (struct sockaddr*)&sockAddr, sockAddrLen) < 0)
- throw NetworkException(strf("cannot connect to %s: %s", addressWithPort, netErrorString()));
+ throw NetworkException(strf("cannot connect to {}: {}", addressWithPort, netErrorString()));
#if defined STAR_SYSTEM_MACOS || defined STAR_SYSTEM_FREEBSD
// Don't generate sigpipe
@@ -161,7 +161,7 @@ TcpServer::TcpServer(HostAddressWithPort const& address) : m_hostAddress(address
m_hostAddress = address;
m_listenSocket = TcpSocket::listen(address);
m_listenSocket->setNonBlocking(true);
- Logger::debug("TcpServer listening on: %s", address);
+ Logger::debug("TcpServer listening on: {}", address);
}
TcpServer::TcpServer(uint16_t port) : TcpServer(HostAddressWithPort("*", port)) {}
@@ -201,7 +201,7 @@ void TcpServer::setAcceptCallback(AcceptCallback callback, unsigned timeout) {
try {
conn = accept(timeout);
} catch (NetworkException const& e) {
- Logger::error("TcpServer caught exception accepting connection %s", outputException(e, false));
+ Logger::error("TcpServer caught exception accepting connection {}", outputException(e, false));
}
if (conn)
@@ -211,7 +211,7 @@ void TcpServer::setAcceptCallback(AcceptCallback callback, unsigned timeout) {
break;
}
} catch (std::exception const& e) {
- Logger::error("TcpServer will close, listener thread caught exception: %s", outputException(e, true));
+ Logger::error("TcpServer will close, listener thread caught exception: {}", outputException(e, true));
m_listenSocket->close();
}
});
diff --git a/source/core/StarThread_unix.cpp b/source/core/StarThread_unix.cpp
index ba635f9..22fd10d 100644
--- a/source/core/StarThread_unix.cpp
+++ b/source/core/StarThread_unix.cpp
@@ -31,21 +31,21 @@ struct ThreadImpl {
#ifdef STAR_SYSTEM_MACOS
// ensure the name is under the max allowed
char tname[MAX_THREAD_NAMELEN];
- snprintf(tname, sizeof(tname), "%s", ptr->name.utf8Ptr());
+ snprintf(tname, sizeof(tname), "{}", ptr->name.utf8Ptr());
pthread_setname_np(tname);
#endif
ptr->function();
} catch (std::exception const& e) {
if (ptr->name.empty())
- Logger::error("Exception caught in Thread: %s", outputException(e, true));
+ Logger::error("Exception caught in Thread: {}", outputException(e, true));
else
- Logger::error("Exception caught in Thread %s: %s", ptr->name, outputException(e, true));
+ Logger::error("Exception caught in Thread {}: {}", ptr->name, outputException(e, true));
} catch (...) {
if (ptr->name.empty())
Logger::error("Unknown exception caught in Thread");
else
- Logger::error("Unknown exception caught in Thread %s", ptr->name);
+ Logger::error("Unknown exception caught in Thread {}", ptr->name);
}
ptr->stopped = true;
return nullptr;
@@ -65,12 +65,12 @@ struct ThreadImpl {
if (ret != 0) {
stopped = true;
joined = true;
- throw StarException(strf("Failed to create thread, error %s", ret));
+ throw StarException(strf("Failed to create thread, error {}", ret));
}
// ensure the name is under the max allowed
char tname[MAX_THREAD_NAMELEN];
- snprintf(tname, sizeof(tname), "%s", name.utf8Ptr());
+ snprintf(tname, sizeof(tname), "{}", name.utf8Ptr());
#ifdef STAR_SYSTEM_FREEBSD
pthread_set_name_np(pthread, tname);
@@ -86,7 +86,7 @@ struct ThreadImpl {
return false;
int ret = pthread_join(pthread, NULL);
if (ret != 0)
- throw StarException(strf("Failed to join thread, error %s", ret));
+ throw StarException(strf("Failed to join thread, error {}", ret));
joined = true;
return true;
}
@@ -242,7 +242,7 @@ void Thread::yield() {
unsigned Thread::numberOfProcessors() {
long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
if (nprocs < 1)
- throw StarException(strf("Could not determine number of CPUs online: %s\n", strerror(errno)));
+ throw StarException(strf("Could not determine number of CPUs online: {}\n", strerror(errno)));
return nprocs;
}
diff --git a/source/core/StarThread_windows.cpp b/source/core/StarThread_windows.cpp
index 86ebbf5..b8df19b 100644
--- a/source/core/StarThread_windows.cpp
+++ b/source/core/StarThread_windows.cpp
@@ -49,14 +49,14 @@ struct ThreadImpl {
ptr->function();
} catch (std::exception const& e) {
if (ptr->name.empty())
- Logger::error("Exception caught in Thread: %s", outputException(e, true));
+ Logger::error("Exception caught in Thread: {}", outputException(e, true));
else
- Logger::error("Exception caught in Thread %s: %s", ptr->name, outputException(e, true));
+ Logger::error("Exception caught in Thread {}: {}", ptr->name, outputException(e, true));
} catch (...) {
if (ptr->name.empty())
Logger::error("Unknown exception caught in Thread");
else
- Logger::error("Unknown exception caught in Thread %s", ptr->name);
+ Logger::error("Unknown exception caught in Thread {}", ptr->name);
}
ptr->stopped = true;
return 0;
diff --git a/source/core/StarTime.cpp b/source/core/StarTime.cpp
index 4d0b516..abb6aae 100644
--- a/source/core/StarTime.cpp
+++ b/source/core/StarTime.cpp
@@ -28,19 +28,19 @@ String Time::printDuration(double time) {
if (time >= 3600) {
int numHours = (int)time / 3600;
- hours = strf("%d hour%s", numHours, numHours == 1 ? "" : "s");
+ hours = strf("{} hour{}", numHours, numHours == 1 ? "" : "s");
}
if (time >= 60) {
int numMinutes = (int)(time / 60) % 60;
- minutes = strf("%s minute%s", numMinutes, numMinutes == 1 ? "" : "s");
+ minutes = strf("{} minute{}", numMinutes, numMinutes == 1 ? "" : "s");
}
if (time >= 1) {
int numSeconds = (int)time % 60;
- seconds = strf("%s second%s", numSeconds, numSeconds == 1 ? "" : "s");
+ seconds = strf("{} second{}", numSeconds, numSeconds == 1 ? "" : "s");
}
int numMilliseconds = round(time * 1000);
- milliseconds = strf("%s millisecond%s", numMilliseconds, numMilliseconds == 1 ? "" : "s");
+ milliseconds = strf("{} millisecond{}", numMilliseconds, numMilliseconds == 1 ? "" : "s");
return String::joinWith(", ", hours, minutes, seconds, milliseconds);
}
diff --git a/source/core/StarTime_unix.cpp b/source/core/StarTime_unix.cpp
index 50ed954..c5259c0 100644
--- a/source/core/StarTime_unix.cpp
+++ b/source/core/StarTime_unix.cpp
@@ -18,13 +18,13 @@ String Time::printDateAndTime(int64_t epochTicks, String format) {
localtime_r(&requestedTime, &ptm);
return format.replaceTags(StringMap<String>{
- {"year", strf("%04d", ptm.tm_year + 1900)},
- {"month", strf("%02d", ptm.tm_mon + 1)},
- {"day", strf("%02d", ptm.tm_mday)},
- {"hours", strf("%02d", ptm.tm_hour)},
- {"minutes", strf("%02d", ptm.tm_min)},
- {"seconds", strf("%02d", ptm.tm_sec)},
- {"millis", strf("%03d", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))}
+ {"year", strf("{:04d}", ptm.tm_year + 1900)},
+ {"month", strf("{:02d}", ptm.tm_mon + 1)},
+ {"day", strf("{:02d}", ptm.tm_mday)},
+ {"hours", strf("{:02d}", ptm.tm_hour)},
+ {"minutes", strf("{:02d}", ptm.tm_min)},
+ {"seconds", strf("{:02d}", ptm.tm_sec)},
+ {"millis", strf("{:03d}", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))}
});
}
diff --git a/source/core/StarTime_windows.cpp b/source/core/StarTime_windows.cpp
index 2b3e797..f1f10b4 100644
--- a/source/core/StarTime_windows.cpp
+++ b/source/core/StarTime_windows.cpp
@@ -14,13 +14,13 @@ String Time::printDateAndTime(int64_t epochTicks, String format) {
ptm = localtime(&requestedTime);
return format.replaceTags(StringMap<String>{
- {"year", strf("%04d", ptm->tm_year + 1900)},
- {"month", strf("%02d", ptm->tm_mon + 1)},
- {"day", strf("%02d", ptm->tm_mday)},
- {"hours", strf("%02d", ptm->tm_hour)},
- {"minutes", strf("%02d", ptm->tm_min)},
- {"seconds", strf("%02d", ptm->tm_sec)},
- {"millis", strf("%03d", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))},
+ {"year", strf("{:04d}", ptm->tm_year + 1900)},
+ {"month", strf("{:02d}", ptm->tm_mon + 1)},
+ {"day", strf("{:02d}", ptm->tm_mday)},
+ {"hours", strf("{:02d}", ptm->tm_hour)},
+ {"minutes", strf("{:02d}", ptm->tm_min)},
+ {"seconds", strf("{:02d}", ptm->tm_sec)},
+ {"millis", strf("{:03d}", (epochTicks % epochTickFrequency()) / (epochTickFrequency() / 1000))},
});
}
diff --git a/source/core/StarUdp.cpp b/source/core/StarUdp.cpp
index 9ff7b48..c38da41 100644
--- a/source/core/StarUdp.cpp
+++ b/source/core/StarUdp.cpp
@@ -23,7 +23,7 @@ size_t UdpSocket::receive(HostAddressWithPort* address, char* data, size_t datas
else if (netErrorInterrupt())
len = 0;
else
- throw NetworkException(strf("udp recv error: %s", netErrorString()));
+ throw NetworkException(strf("udp recv error: {}", netErrorString()));
}
if (address)
@@ -47,7 +47,7 @@ size_t UdpSocket::send(HostAddressWithPort const& address, char const* data, siz
else if (netErrorInterrupt())
len = 0;
else
- throw NetworkException(strf("udp send error: %s", netErrorString()));
+ throw NetworkException(strf("udp send error: {}", netErrorString()));
}
return len;
@@ -57,7 +57,7 @@ UdpServer::UdpServer(HostAddressWithPort const& address)
: m_hostAddress(address), m_listenSocket(make_shared<UdpSocket>(m_hostAddress.address().mode())) {
m_listenSocket->setNonBlocking(true);
m_listenSocket->bind(m_hostAddress);
- Logger::debug("UdpServer listening on: %s", m_hostAddress);
+ Logger::debug("UdpServer listening on: {}", m_hostAddress);
}
UdpServer::~UdpServer() {
diff --git a/source/core/StarUnicode.cpp b/source/core/StarUnicode.cpp
index 008df96..01e660b 100644
--- a/source/core/StarUnicode.cpp
+++ b/source/core/StarUnicode.cpp
@@ -12,7 +12,7 @@ void throwMissingUtf8End() {
}
void throwInvalidUtf32CodePoint(Utf32Type val) {
- throw UnicodeException::format("Invalid UTF-32 code point %s encountered while trying to encode UTF-8", (int32_t)val);
+ throw UnicodeException::format("Invalid UTF-32 code point {} encountered while trying to encode UTF-8", (int32_t)val);
}
size_t utf8Length(const Utf8Type* utf8, size_t remain) {
diff --git a/source/core/StarUuid.cpp b/source/core/StarUuid.cpp
index 11121b6..6890e5e 100644
--- a/source/core/StarUuid.cpp
+++ b/source/core/StarUuid.cpp
@@ -9,7 +9,7 @@ Uuid::Uuid() : Uuid(Random::randBytes(UuidSize)) {}
Uuid::Uuid(ByteArray const& bytes) {
if (bytes.size() != UuidSize)
- throw UuidException(strf("Size mismatch in reading Uuid from ByteArray: %s vs %s", bytes.size(), UuidSize));
+ throw UuidException(strf("Size mismatch in reading Uuid from ByteArray: {} vs {}", bytes.size(), UuidSize));
bytes.copyTo(m_data.ptr(), UuidSize);
}
diff --git a/source/core/StarWorkerPool.cpp b/source/core/StarWorkerPool.cpp
index fa37a57..2a7003d 100644
--- a/source/core/StarWorkerPool.cpp
+++ b/source/core/StarWorkerPool.cpp
@@ -125,7 +125,7 @@ WorkerPoolHandle WorkerPool::addWork(function<void()> work) {
}
WorkerPool::WorkerThread::WorkerThread(WorkerPool* parent)
- : Thread(strf("WorkerThread for WorkerPool '%s'", parent->m_name)),
+ : Thread(strf("WorkerThread for WorkerPool '{}'", parent->m_name)),
parent(parent),
shouldStop(false),
waiting(false) {
diff --git a/source/frontend/StarActionBar.cpp b/source/frontend/StarActionBar.cpp
index 6c9b48c..5ccff7b 100644
--- a/source/frontend/StarActionBar.cpp
+++ b/source/frontend/StarActionBar.cpp
@@ -31,15 +31,15 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
GuiReader reader;
for (uint8_t i = 0; i < m_player->inventory()->customBarIndexes(); ++i) {
- reader.registerCallback(strf("customBar%sL", i + 1), bind(&ActionBar::customBarClick, this, i, true));
- reader.registerCallback(strf("customBar%sR", i + 1), bind(&ActionBar::customBarClick, this, i, false));
+ reader.registerCallback(strf("customBar{}L", i + 1), bind(&ActionBar::customBarClick, this, i, true));
+ reader.registerCallback(strf("customBar{}R", i + 1), bind(&ActionBar::customBarClick, this, i, false));
- reader.registerCallback(strf("customBar%sL.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, true));
- reader.registerCallback(strf("customBar%sR.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, false));
+ reader.registerCallback(strf("customBar{}L.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, true));
+ reader.registerCallback(strf("customBar{}R.right", i + 1), bind(&ActionBar::customBarClickRight, this, i, false));
}
for (uint8_t i = 0; i < EssentialItemCount; ++i)
- reader.registerCallback(strf("essentialBar%s", i + 1), bind(&ActionBar::essentialBarClick, this, i));
+ reader.registerCallback(strf("essentialBar{}", i + 1), bind(&ActionBar::essentialBarClick, this, i));
reader.registerCallback("pickupToActionBar", [=](Widget* widget) {
auto button = as<ButtonWidget>(widget);
@@ -53,10 +53,10 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
reader.construct(m_config.get("paneLayout"), this);
for (uint8_t i = 0; i < m_player->inventory()->customBarIndexes(); ++i) {
- auto customBarLeft = fetchChild<ItemSlotWidget>(strf("customBar%sL", i + 1));
- auto customBarRight = fetchChild<ItemSlotWidget>(strf("customBar%sR", i + 1));
- auto customBarLeftOverlay = fetchChild<ImageWidget>(strf("customBar%sLOverlay", i + 1));
- auto customBarRightOverlay = fetchChild<ImageWidget>(strf("customBar%sROverlay", i + 1));
+ auto customBarLeft = fetchChild<ItemSlotWidget>(strf("customBar{}L", i + 1));
+ auto customBarRight = fetchChild<ItemSlotWidget>(strf("customBar{}R", i + 1));
+ auto customBarLeftOverlay = fetchChild<ImageWidget>(strf("customBar{}LOverlay", i + 1));
+ auto customBarRightOverlay = fetchChild<ImageWidget>(strf("customBar{}ROverlay", i + 1));
TextPositioning countPosition = {jsonToVec2F(m_config.get("countMidAnchor")), HorizontalAnchor::HMidAnchor};
customBarLeft->setCountPosition(countPosition);
@@ -69,7 +69,7 @@ ActionBar::ActionBar(MainInterfacePaneManager* paneManager, PlayerPtr player) {
m_customSelectedWidget = fetchChild<ImageWidget>("customSelect");
for (uint8_t i = 0; i < EssentialItemCount; ++i)
- m_essentialBarWidgets.append(fetchChild<ItemSlotWidget>(strf("essentialBar%s", i + 1)));
+ m_essentialBarWidgets.append(fetchChild<ItemSlotWidget>(strf("essentialBar{}", i + 1)));
m_essentialSelectedWidget = fetchChild<ImageWidget>("essentialSelect");
}
diff --git a/source/frontend/StarBookmarkInterface.cpp b/source/frontend/StarBookmarkInterface.cpp
index 132ac13..d11ac33 100644
--- a/source/frontend/StarBookmarkInterface.cpp
+++ b/source/frontend/StarBookmarkInterface.cpp
@@ -46,7 +46,7 @@ void EditBookmarkDialog::show() {
}
auto assets = Root::singleton().assets();
- fetchChild<ImageWidget>("imgIcon")->setImage(strf("/interface/bookmarks/icons/%s.png", m_bookmark.icon));
+ fetchChild<ImageWidget>("imgIcon")->setImage(strf("/interface/bookmarks/icons/{}.png", m_bookmark.icon));
fetchChild<LabelWidget>("lblPlanetName")->setText(m_bookmark.targetName);
fetchChild<TextBoxWidget>("name")->setText(m_bookmark.bookmarkName, false);
@@ -75,7 +75,7 @@ void EditBookmarkDialog::close() {
void setupBookmarkEntry(WidgetPtr const& entry, TeleportBookmark const& bookmark) {
entry->fetchChild<LabelWidget>("name")->setText(bookmark.bookmarkName);
entry->fetchChild<LabelWidget>("planetName")->setText(bookmark.targetName);
- entry->fetchChild<ImageWidget>("icon")->setImage(strf("/interface/bookmarks/icons/%s.png", bookmark.icon));
+ entry->fetchChild<ImageWidget>("icon")->setImage(strf("/interface/bookmarks/icons/{}.png", bookmark.icon));
}
}
diff --git a/source/frontend/StarCharCreation.cpp b/source/frontend/StarCharCreation.cpp
index fd617df..c1e0f1d 100644
--- a/source/frontend/StarCharCreation.cpp
+++ b/source/frontend/StarCharCreation.cpp
@@ -165,7 +165,7 @@ void CharCreationPane::createPlayer() {
throw CharCreationException("The charPreview portrait has the wrong type.");
}
} catch (CharCreationException const& e) {
- Logger::error("Character Preview portrait was not found in the json specification. %s", outputException(e, false));
+ Logger::error("Character Preview portrait was not found in the json specification. {}", outputException(e, false));
}
}
@@ -269,15 +269,15 @@ void CharCreationPane::changed() {
fetchChild<LabelWidget>("labelPortrait")->setText(labels[8]);
fetchChild<LabelWidget>("labelPersonality")->setText(labels[9]);
- fetchChild<ButtonWidget>(strf("species.%s", m_speciesChoice))->check();
- fetchChild<ButtonWidget>(strf("gender.%s", genderIdx))->check();
- auto modeButton = fetchChild<ButtonWidget>(strf("mode.%s", m_modeChoice));
+ fetchChild<ButtonWidget>(strf("species.{}", m_speciesChoice))->check();
+ fetchChild<ButtonWidget>(strf("gender.{}", genderIdx))->check();
+ auto modeButton = fetchChild<ButtonWidget>(strf("mode.{}", m_modeChoice));
modeButton->check();
setLabel("labelMode", modeButton->data().getString("description", "fail"));
// Update the gender images for the new species
for (size_t i = 0; i < species.genderOptions.size(); i++)
- fetchChild<ButtonWidget>(strf("gender.%s", i))->setOverlayImage(species.genderOptions[i].image);
+ fetchChild<ButtonWidget>(strf("gender.{}", i))->setOverlayImage(species.genderOptions[i].image);
for (auto const& nameDefPair : root.speciesDatabase()->allSpecies()) {
String name;
@@ -286,7 +286,7 @@ void CharCreationPane::changed() {
// NOTE: Probably not hot enough to matter, but this contains and indexOf makes this loop
// O(n^2). This is less than ideal.
if (m_speciesList.contains(name)) {
- auto bw = fetchChild<ButtonWidget>(strf("species.%s", m_speciesList.indexOf(name)));
+ auto bw = fetchChild<ButtonWidget>(strf("species.{}", m_speciesList.indexOf(name)));
if (bw)
bw->setOverlayImage(def->options().genderOptions[genderIdx].characterImage);
}
diff --git a/source/frontend/StarChat.cpp b/source/frontend/StarChat.cpp
index 4af8930..7b75f2d 100644
--- a/source/frontend/StarChat.cpp
+++ b/source/frontend/StarChat.cpp
@@ -183,7 +183,7 @@ void Chat::addMessages(List<ChatReceivedMessage> const& messages, bool showPane)
guiContext.setFontSize(m_fontSize);
StringList lines;
if (message.fromNick != "" && message.portrait == "")
- lines = guiContext.wrapInterfaceText(strf("<%s> %s", message.fromNick, message.text), wrapWidth);
+ lines = guiContext.wrapInterfaceText(strf("<{}> {}", message.fromNick, message.text), wrapWidth);
else
lines = guiContext.wrapInterfaceText(message.text, wrapWidth);
@@ -196,9 +196,9 @@ void Chat::addMessages(List<ChatReceivedMessage> const& messages, bool showPane)
}
if (message.fromNick != "")
- Logger::info("Chat: <%s> %s", message.fromNick, message.text);
+ Logger::info("Chat: <{}> {}", message.fromNick, message.text);
else
- Logger::info("Chat: %s", message.text);
+ Logger::info("Chat: {}", message.text);
}
if (showPane) {
diff --git a/source/frontend/StarCinematic.cpp b/source/frontend/StarCinematic.cpp
index a7a13ee..7408264 100644
--- a/source/frontend/StarCinematic.cpp
+++ b/source/frontend/StarCinematic.cpp
@@ -189,7 +189,7 @@ void Cinematic::render() {
m_completable = true;
if (!values.alpha)
continue;
- auto frame = strf("%s", ((int)values.frame) % panel->animationFrames);
+ auto frame = strf("{}", ((int)values.frame) % panel->animationFrames);
auto alphaColor = Color::rgbaf(1.0f, 1.0f, 1.0f, values.alpha);
for (auto const& d : panel->drawables) {
Drawable drawable = Drawable(d.set("image", d.getString("image").replaceTags(StringMap<String>{{"species", playerSpecies}, {"frame", frame}})));
diff --git a/source/frontend/StarClientCommandProcessor.cpp b/source/frontend/StarClientCommandProcessor.cpp
index bf9a434..f006d8e 100644
--- a/source/frontend/StarClientCommandProcessor.cpp
+++ b/source/frontend/StarClientCommandProcessor.cpp
@@ -92,11 +92,11 @@ StringList ClientCommandProcessor::handleCommand(String const& commandLine) {
}
return result;
} catch (ShellParsingException const& e) {
- Logger::error("Shell parsing exception: %s", outputException(e, false));
+ Logger::error("Shell parsing exception: {}", outputException(e, false));
return {"Shell parsing exception"};
} catch (std::exception const& e) {
- Logger::error("Exception caught handling client command %s: %s", commandLine, outputException(e, true));
- return {strf("Exception caught handling client command %s", commandLine)};
+ Logger::error("Exception caught handling client command {}: {}", commandLine, outputException(e, true));
+ return {strf("Exception caught handling client command {}", commandLine)};
}
}
@@ -114,7 +114,7 @@ String ClientCommandProcessor::reload() {
}
String ClientCommandProcessor::whoami() {
- return strf("Client: You are %s. You are %san Admin.",
+ return strf("Client: You are {}. You are {}an Admin.",
m_universeClient->mainPlayer()->name(), m_universeClient->mainPlayer()->isAdmin() ? "" : "not ");
}
@@ -122,7 +122,7 @@ String ClientCommandProcessor::gravity() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
- return strf("%s", m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
+ return strf("{}", m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
}
String ClientCommandProcessor::debug() {
@@ -130,14 +130,14 @@ String ClientCommandProcessor::debug() {
return "You must be an admin to use this command.";
m_debugDisplayEnabled = !m_debugDisplayEnabled;
- return strf("Debug display %s", m_debugDisplayEnabled ? "enabled" : "disabled");
+ return strf("Debug display {}", m_debugDisplayEnabled ? "enabled" : "disabled");
}
String ClientCommandProcessor::boxes() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
- return strf("Geometry debug display %s",
+ return strf("Geometry debug display {}",
m_universeClient->worldClient()->toggleCollisionDebug()
? "enabled" : "disabled");
}
@@ -146,7 +146,7 @@ String ClientCommandProcessor::fullbright() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
- return strf("Fullbright render lighting %s",
+ return strf("Fullbright render lighting {}",
m_universeClient->worldClient()->toggleFullbright()
? "enabled" : "disabled");
}
@@ -156,7 +156,7 @@ String ClientCommandProcessor::setGravity(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->worldClient()->overrideGravity(lexicalCast<float>(arguments.at(0)));
- return strf("Gravity set to %s, the change is LOCAL ONLY", arguments.at(0));
+ return strf("Gravity set to {}, the change is LOCAL ONLY", arguments.at(0));
}
String ClientCommandProcessor::resetGravity() {
@@ -172,13 +172,13 @@ String ClientCommandProcessor::fixedCamera() {
return "You must be an admin to use this command.";
m_fixedCameraEnabled = !m_fixedCameraEnabled;
- return strf("Fixed camera %s", m_fixedCameraEnabled ? "enabled" : "disabled");
+ return strf("Fixed camera {}", m_fixedCameraEnabled ? "enabled" : "disabled");
}
String ClientCommandProcessor::monochromeLighting() {
bool monochrome = !Root::singleton().configuration()->get("monochromeLighting").toBool();
Root::singleton().configuration()->set("monochromeLighting", monochrome);
- return strf("Monochrome lighting %s", monochrome ? "enabled" : "disabled");
+ return strf("Monochrome lighting {}", monochrome ? "enabled" : "disabled");
}
String ClientCommandProcessor::radioMessage(StringList const& arguments) {
@@ -222,7 +222,7 @@ String ClientCommandProcessor::completeQuest(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->questManager()->getQuest(arguments.at(0))->complete();
- return strf("Quest %s complete", arguments.at(0));
+ return strf("Quest {} complete", arguments.at(0));
}
String ClientCommandProcessor::failQuest(StringList const& arguments) {
@@ -230,7 +230,7 @@ String ClientCommandProcessor::failQuest(StringList const& arguments) {
return "You must be an admin to use this command.";
m_universeClient->questManager()->getQuest(arguments.at(0))->fail();
- return strf("Quest %s failed", arguments.at(0));
+ return strf("Quest {} failed", arguments.at(0));
}
String ClientCommandProcessor::previewNewQuest(StringList const& arguments) {
@@ -269,12 +269,12 @@ String ClientCommandProcessor::clearScannedObjects() {
}
String ClientCommandProcessor::playTime() {
- return strf("Total play time: %s", Time::printDuration(m_universeClient->mainPlayer()->log()->playTime()));
+ return strf("Total play time: {}", Time::printDuration(m_universeClient->mainPlayer()->log()->playTime()));
}
String ClientCommandProcessor::deathCount() {
auto deaths = m_universeClient->mainPlayer()->log()->deathCount();
- return strf("Total deaths: %s%s", deaths, deaths == 0 ? ". Well done!" : "");
+ return strf("Total deaths: {}{}", deaths, deaths == 0 ? ". Well done!" : "");
}
String ClientCommandProcessor::cinema(StringList const& arguments) {
@@ -284,7 +284,7 @@ String ClientCommandProcessor::cinema(StringList const& arguments) {
m_cinematicOverlay->load(Root::singleton().assets()->json(arguments.at(0)));
if (arguments.size() > 1)
m_cinematicOverlay->setTime(lexicalCast<float>(arguments.at(1)));
- return strf("Started cinematic %s at %s", arguments.at(0), arguments.size() > 1 ? arguments.at(1) : "beginning");
+ return strf("Started cinematic {} at {}", arguments.at(0), arguments.size() > 1 ? arguments.at(1) : "beginning");
}
String ClientCommandProcessor::suicide() {
@@ -315,7 +315,7 @@ String ClientCommandProcessor::statistic(StringList const& arguments) {
StringList values;
for (String const& statName : arguments) {
- values.append(strf("%s = %s", statName, m_universeClient->statistics()->stat(statName)));
+ values.append(strf("{} = {}", statName, m_universeClient->statistics()->stat(statName)));
}
return values.join("\n");
}
@@ -331,9 +331,9 @@ String ClientCommandProcessor::giveEssentialItem(StringList const& arguments) {
auto item = Root::singleton().itemDatabase()->item(ItemDescriptor(arguments.at(0)));
auto slot = EssentialItemNames.getLeft(arguments.at(1));
m_universeClient->mainPlayer()->inventory()->setEssentialItem(slot, item);
- return strf("Put %s in player slot %s", item->name(), arguments.at(1));
+ return strf("Put {} in player slot {}", item->name(), arguments.at(1));
} catch (MapException const& e) {
- return strf("Invalid essential item slot %s.", arguments.at(1));
+ return strf("Invalid essential item slot {}.", arguments.at(1));
}
}
@@ -345,7 +345,7 @@ String ClientCommandProcessor::makeTechAvailable(StringList const& arguments) {
return "Not enouch arguments to /maketechavailable";
m_universeClient->mainPlayer()->techs()->makeAvailable(arguments.at(0));
- return strf("Added %s to player's visible techs", arguments.at(0));
+ return strf("Added {} to player's visible techs", arguments.at(0));
}
String ClientCommandProcessor::enableTech(StringList const& arguments) {
@@ -357,7 +357,7 @@ String ClientCommandProcessor::enableTech(StringList const& arguments) {
m_universeClient->mainPlayer()->techs()->makeAvailable(arguments.at(0));
m_universeClient->mainPlayer()->techs()->enable(arguments.at(0));
- return strf("Player tech %s enabled", arguments.at(0));
+ return strf("Player tech {} enabled", arguments.at(0));
}
String ClientCommandProcessor::upgradeShip(StringList const& arguments) {
diff --git a/source/frontend/StarCodexInterface.cpp b/source/frontend/StarCodexInterface.cpp
index f841c5d..aca0930 100644
--- a/source/frontend/StarCodexInterface.cpp
+++ b/source/frontend/StarCodexInterface.cpp
@@ -126,7 +126,7 @@ void CodexInterface::setupPageText() {
if (m_currentCodex) {
m_pageContent->setText(m_currentCodex->page(m_currentPage));
m_pageLabelWidget->show();
- m_pageNumberWidget->setText(strf("%d of %d", m_currentPage + 1, m_currentCodex->pageCount()));
+ m_pageNumberWidget->setText(strf("{} of {}", m_currentPage + 1, m_currentCodex->pageCount()));
m_titleLabel->setText(m_currentCodex->title());
m_nextPageButton->setEnabled(m_currentPage < m_currentCodex->pageCount() - 1);
m_prevPageButton->setEnabled(m_currentPage > 0);
diff --git a/source/frontend/StarContainerInterface.cpp b/source/frontend/StarContainerInterface.cpp
index e94c25c..9f80a94 100644
--- a/source/frontend/StarContainerInterface.cpp
+++ b/source/frontend/StarContainerInterface.cpp
@@ -129,7 +129,7 @@ ContainerPane::ContainerPane(WorldClientPtr worldClient, PlayerPtr player, Conta
m_reader.construct(guiConfig.get("gui"), this);
if (auto countWidget = fetchChild<LabelWidget>("count"))
- countWidget->setText(countWidget->text().replace("<slots>", strf("%s", container->containerSize())));
+ countWidget->setText(countWidget->text().replace("<slots>", strf("{}", container->containerSize())));
m_itemBag = make_shared<ItemBag>(container->containerSize());
auto items = container->containerItems();
diff --git a/source/frontend/StarCraftingInterface.cpp b/source/frontend/StarCraftingInterface.cpp
index 01f7e3c..f3cedf5 100644
--- a/source/frontend/StarCraftingInterface.cpp
+++ b/source/frontend/StarCraftingInterface.cpp
@@ -294,7 +294,7 @@ void CraftingPane::update() {
updateCraftButtons();
}
- setLabel("lblPlayerMoney", strf("%s", (int)m_player->currency("money")));
+ setLabel("lblPlayerMoney", strf("{}", (int)m_player->currency("money")));
Pane::update();
}
@@ -405,7 +405,7 @@ void CraftingPane::setupWidget(WidgetPtr const& widget, ItemRecipe const& recipe
String name = item->friendlyName();
if (recipe.output.count() > 1)
- name = strf("%s (x%s)", name, recipe.output.count());
+ name = strf("{} (x{})", name, recipe.output.count());
auto itemName = widget->fetchChild<LabelWidget>("itemName");
auto notcraftableoverlay = widget->fetchChild<ImageWidget>("notcraftableoverlay");
@@ -421,7 +421,7 @@ void CraftingPane::setupWidget(WidgetPtr const& widget, ItemRecipe const& recipe
}
if (price > 0) {
- widget->setLabel("priceLabel", strf("%s", price));
+ widget->setLabel("priceLabel", strf("{}", price));
if (auto icon = widget->fetchChild<ImageWidget>("moneyIcon"))
icon->setVisibility(true);
} else {
@@ -463,7 +463,7 @@ PanePtr CraftingPane::setupTooltip(ItemRecipe const& recipe) {
auto widget = guiList->addItem();
widget->fetchChild<LabelWidget>("itemName")->setText(item->friendlyName());
auto countWidget = widget->fetchChild<LabelWidget>("count");
- countWidget->setText(strf("%s/%s", availableCount, requiredCount));
+ countWidget->setText(strf("{}/{}", availableCount, requiredCount));
if (availableCount < requiredCount)
countWidget->setColor(Color::Red);
else
@@ -616,7 +616,7 @@ void CraftingPane::countTextChanged() {
void CraftingPane::countChanged() {
if (m_textBox)
- m_textBox->setText(strf("x%s", m_count), false);
+ m_textBox->setText(strf("x{}", m_count), false);
}
List<ItemRecipe> CraftingPane::determineRecipes() {
diff --git a/source/frontend/StarGraphicsMenu.cpp b/source/frontend/StarGraphicsMenu.cpp
index 80aba55..3f0778c 100644
--- a/source/frontend/StarGraphicsMenu.cpp
+++ b/source/frontend/StarGraphicsMenu.cpp
@@ -148,7 +148,7 @@ void GraphicsMenu::syncGui() {
} else {
resSlider->setVal(m_resList.size() - 1);
}
- fetchChild<LabelWidget>("resValueLabel")->setText(strf("%dx%d", res[0], res[1]));
+ fetchChild<LabelWidget>("resValueLabel")->setText(strf("{}x{}", res[0], res[1]));
auto zoomSlider = fetchChild<SliderBarWidget>("zoomSlider");
auto zoomIt = std::lower_bound(m_zoomList.begin(), m_zoomList.end(), m_localChanges.get("zoomLevel").toFloat());
@@ -159,7 +159,7 @@ void GraphicsMenu::syncGui() {
} else {
zoomSlider->setVal(m_zoomList.size() - 1);
}
- fetchChild<LabelWidget>("zoomValueLabel")->setText(strf("%dx", m_localChanges.get("zoomLevel").toInt()));
+ fetchChild<LabelWidget>("zoomValueLabel")->setText(strf("{}x", m_localChanges.get("zoomLevel").toInt()));
fetchChild<ButtonWidget>("speechBubbleCheckbox")->setChecked(m_localChanges.get("speechBubbles").toBool());
diff --git a/source/frontend/StarInventory.cpp b/source/frontend/StarInventory.cpp
index 72d91e6..e54f288 100644
--- a/source/frontend/StarInventory.cpp
+++ b/source/frontend/StarInventory.cpp
@@ -87,7 +87,7 @@ InventoryPane::InventoryPane(MainInterface* parent, PlayerPtr player, ContainerI
for (auto name : bagOrder) {
auto itemGrid = itemBagConfig.get(name).getString("itemGrid");
invWindowReader.registerCallback(itemGrid, bind(leftClickCallback, name, _1));
- invWindowReader.registerCallback(strf("%s.right", itemGrid), bind(bagGridCallback, name, _1));
+ invWindowReader.registerCallback(strf("{}.right", itemGrid), bind(bagGridCallback, name, _1));
}
invWindowReader.registerCallback("close", [=](Widget*) {
@@ -195,7 +195,7 @@ PanePtr InventoryPane::createTooltip(Vec2I const& screenPosition) {
auto techDatabase = Root::singleton().techDatabase();
for (auto const& p : TechTypeNames) {
- if (auto techIcon = fetchChild<ImageWidget>(strf("tech%s", p.second))) {
+ if (auto techIcon = fetchChild<ImageWidget>(strf("tech{}", p.second))) {
if (techIcon->screenBoundRect().contains(screenPosition)) {
if (auto techModule = m_player->techs()->equippedTechs().maybe(p.first))
return SimpleTooltipBuilder::buildTooltip(techDatabase->tech(*techModule).description);
@@ -277,7 +277,7 @@ void InventoryPane::update() {
auto techDatabase = Root::singleton().techDatabase();
for (auto const& p : TechTypeNames) {
- if (auto techIcon = fetchChild<ImageWidget>(strf("tech%s", p.second))) {
+ if (auto techIcon = fetchChild<ImageWidget>(strf("tech{}", p.second))) {
if (auto techModule = m_player->techs()->equippedTechs().maybe(p.first))
techIcon->setImage(techDatabase->tech(*techModule).icon);
else
@@ -315,25 +315,25 @@ void InventoryPane::update() {
techOverlay->setVisibility(m_player->techOverridden());
auto healthLabel = fetchChild<LabelWidget>("healthtext");
- healthLabel->setText(strf("%d", m_player->maxHealth()));
+ healthLabel->setText(strf("{}", m_player->maxHealth()));
auto energyLabel = fetchChild<LabelWidget>("energytext");
- energyLabel->setText(strf("%d", m_player->maxEnergy()));
+ energyLabel->setText(strf("{}", m_player->maxEnergy()));
auto weaponLabel = fetchChild<LabelWidget>("weapontext");
- weaponLabel->setText(strf("%d%%", ceil(m_player->powerMultiplier() * 100)));
+ weaponLabel->setText(strf("{}%", ceil(m_player->powerMultiplier() * 100)));
auto defenseLabel = fetchChild<LabelWidget>("defensetext");
if (m_player->protection() == 0)
defenseLabel->setText("--");
else
- defenseLabel->setText(strf("%d", ceil(m_player->protection())));
+ defenseLabel->setText(strf("{}", ceil(m_player->protection())));
auto moneyLabel = fetchChild<LabelWidget>("lblMoney");
- moneyLabel->setText(strf("%d", m_player->currency("money")));
+ moneyLabel->setText(strf("{}", m_player->currency("money")));
if (m_player->currency("essence") > 0) {
fetchChild<ImageWidget>("imgEssenceIcon")->show();
auto essenceLabel = fetchChild<LabelWidget>("lblEssence");
essenceLabel->show();
- essenceLabel->setText(strf("%d", m_player->currency("essence")));
+ essenceLabel->setText(strf("{}", m_player->currency("essence")));
} else {
fetchChild<ImageWidget>("imgEssenceIcon")->hide();
fetchChild<LabelWidget>("lblEssence")->hide();
@@ -357,14 +357,14 @@ void InventoryPane::update() {
auto attackLabel = fetchChild<LabelWidget>("companionAttackStat");
if (auto attack = pet->stat("attack")) {
- attackLabel->setText(strf("%.0f", *attack));
+ attackLabel->setText(strf("{:.0f}", *attack));
} else {
attackLabel->setText("");
}
auto defenseLabel = fetchChild<LabelWidget>("companionDefenseStat");
if (auto defense = pet->stat("defense")) {
- defenseLabel->setText(strf("%.0f", *defense));
+ defenseLabel->setText(strf("{:.0f}", *defense));
} else {
defenseLabel->setText("");
}
diff --git a/source/frontend/StarItemTooltip.cpp b/source/frontend/StarItemTooltip.cpp
index 9138349..46a2d85 100644
--- a/source/frontend/StarItemTooltip.cpp
+++ b/source/frontend/StarItemTooltip.cpp
@@ -81,7 +81,7 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
container->fetchChild<ItemSlotWidget>("icon")->setItem(item);
container->setLabel("nameLabel", item->name());
- container->setLabel("countLabel", strf("%s", item->count()));
+ container->setLabel("countLabel", strf("{}", item->count()));
container->setLabel("rarityLabel", RarityNames.getRight(item->rarity()).titleCase());
@@ -90,8 +90,8 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
else
container->setLabel("handednessLabel", "1-Handed");
- container->setLabel("countLabel", strf("%s", item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
- container->setLabel("priceLabel", strf("%s", (int)item->price()));
+ container->setLabel("countLabel", strf("{}", item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
+ container->setLabel("priceLabel", strf("{}", (int)item->price()));
if (auto objectItem = as<ObjectItem>(item)) {
try {
@@ -103,13 +103,13 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
}
if (objectItem->tooltipKind() == "container")
- container->setLabel("slotCountLabel", strf("Holds %s Items", objectItem->instanceValue("slotCount")));
+ container->setLabel("slotCountLabel", strf("Holds {} Items", objectItem->instanceValue("slotCount")));
title = object->shortDescription();
subTitle = categoryDisplayName(object->category());
description = object->description();
} catch (StarException const& e) {
- Logger::error("Failed to instantiate object for object item tooltip. %s", outputException(e, false));
+ Logger::error("Failed to instantiate object for object item tooltip. {}", outputException(e, false));
}
} else {
if (container->containsChild("objectImage")) {
@@ -137,9 +137,9 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
}
if (auto fireable = as<FireableItem>(item)) {
- container->setLabel("cooldownTimeLabel", strf("%.2f", fireable->cooldownTime()));
- container->setLabel("windupTimeLabel", strf("%.2f", fireable->windupTime()));
- container->setLabel("speedLabel", strf("%.2f", 1.0f / (fireable->cooldownTime() + fireable->windupTime())));
+ container->setLabel("cooldownTimeLabel", strf("{:.2f}", fireable->cooldownTime()));
+ container->setLabel("windupTimeLabel", strf("{:.2f}", fireable->windupTime()));
+ container->setLabel("speedLabel", strf("{:.2f}", 1.0f / (fireable->cooldownTime() + fireable->windupTime())));
}
if (container->containsChild("largeImage")) {
@@ -198,21 +198,21 @@ void ItemTooltipBuilder::describePersistentEffect(
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(baseMultiplier->statName).getString("icon"));
- listItem->setLabel("statusLabel", strf("%s%%", (baseMultiplier->baseMultiplier - 1) * 100));
+ listItem->setLabel("statusLabel", strf("{}%", (baseMultiplier->baseMultiplier - 1) * 100));
}
} else if (auto valueModifier = modifierEffect->ptr<StatValueModifier>()) {
if (statsConfig.contains(valueModifier->statName)) {
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(valueModifier->statName).getString("icon"));
- listItem->setLabel("statusLabel", strf("%s%s", valueModifier->value < 0 ? "-" : "", valueModifier->value));
+ listItem->setLabel("statusLabel", strf("{}{}", valueModifier->value < 0 ? "-" : "", valueModifier->value));
}
} else if (auto effectiveMultiplier = modifierEffect->ptr<StatEffectiveMultiplier>()) {
if (statsConfig.contains(effectiveMultiplier->statName)) {
auto listItem = container->addItem();
listItem->fetchChild<ImageWidget>("statusImage")
->setImage(statsConfig.get(effectiveMultiplier->statName).getString("icon"));
- listItem->setLabel("statusLabel", strf("%s%%", (effectiveMultiplier->effectiveMultiplier - 1) * 100));
+ listItem->setLabel("statusLabel", strf("{}%", (effectiveMultiplier->effectiveMultiplier - 1) * 100));
}
}
}
diff --git a/source/frontend/StarKeybindingsMenu.cpp b/source/frontend/StarKeybindingsMenu.cpp
index 85b5b56..c07dae8 100644
--- a/source/frontend/StarKeybindingsMenu.cpp
+++ b/source/frontend/StarKeybindingsMenu.cpp
@@ -128,7 +128,7 @@ void KeybindingsMenu::buildListsFromConfig() {
for (auto const& bindingEntry : bindings.get(actionString).iterateArray())
inputDesc.append(inputDescriptorFromJson(bindingEntry));
} catch (StarException const& e) {
- Logger::warn("Could not load keybinding for %s. %s\n", actionString, e.what());
+ Logger::warn("Could not load keybinding for {}. {}\n", actionString, e.what());
}
m_childToAction.insert({newListMember->fetchChild<ButtonWidget>("boundKeys").get(), action});
diff --git a/source/frontend/StarMainInterface.cpp b/source/frontend/StarMainInterface.cpp
index 8a3d18b..9d3c3a5 100644
--- a/source/frontend/StarMainInterface.cpp
+++ b/source/frontend/StarMainInterface.cpp
@@ -681,7 +681,7 @@ void MainInterface::update() {
}
m_messageOverflow++;
- m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", strf("%s", m_messageOverflow));
+ m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", strf("{}", m_messageOverflow));
m_overflowMessage->cooldown = m_config->messageTime;
if (auto oldest = m_messages.sorted([](GuiMessagePtr a, GuiMessagePtr b) { return a->cooldown < b->cooldown; }).maybeFirst())
m_overflowMessage->cooldown = oldest.value()->cooldown;
@@ -862,11 +862,11 @@ void MainInterface::queueItemPickupText(ItemPtr const& item) {
auto countMessPair = m_itemDropMessages.get(descriptor.singular());
auto newCount = item->count() + countMessPair.first;
auto message = countMessPair.second;
- message->message = strf("%s - %s", item->friendlyName(), newCount);
+ message->message = strf("{} - {}", item->friendlyName(), newCount);
message->cooldown = m_config->messageTime;
m_itemDropMessages[descriptor.singular()] = {newCount, message};
} else {
- auto message = make_shared<GuiMessage>(strf("%s - %s", item->friendlyName(), item->count()), m_config->messageTime);
+ auto message = make_shared<GuiMessage>(strf("{} - {}", item->friendlyName(), item->count()), m_config->messageTime);
m_messages.append(message);
m_itemDropMessages[descriptor.singular()] = {item->count(), message};
}
@@ -929,7 +929,7 @@ PanePtr MainInterface::createEscapeDialog() {
});
escapeDialogReader.construct(assets->json("/interface.config:escapeDialog"), escapeDialogPtr);
- escapeDialog->fetchChild<LabelWidget>("lblversion")->setText(strf("Starbound - %s (%s)", StarVersionString, StarArchitectureString));
+ escapeDialog->fetchChild<LabelWidget>("lblversion")->setText(strf("Starbound - {} ({})", StarVersionString, StarArchitectureString));
return escapeDialog;
}
@@ -1268,7 +1268,7 @@ void MainInterface::renderDebug() {
int counter = 0;
for (auto const& pair : logMapValues) {
TextPositioning positioning = {Vec2F(m_config->debugOffset[0], windowHeight() - m_config->debugOffset[1] - m_config->fontSize * interfaceScale() * counter)};
- m_debugTextRect.combine(m_guiContext->determineTextSize(strf("%s: %s", pair.first, pair.second), positioning).padded(m_config->debugBackgroundPad));
+ m_debugTextRect.combine(m_guiContext->determineTextSize(strf("{}: {}", pair.first, pair.second), positioning).padded(m_config->debugBackgroundPad));
++counter;
}
@@ -1281,7 +1281,7 @@ void MainInterface::renderDebug() {
counter = 0;
for (auto const& pair : logMapValues) {
TextPositioning positioning = {Vec2F(m_config->debugOffset[0], windowHeight() - m_config->debugOffset[1] - m_config->fontSize * interfaceScale() * counter)};
- m_guiContext->renderText(strf("%s: %s", pair.first, pair.second), positioning);
+ m_guiContext->renderText(strf("{}: {}", pair.first, pair.second), positioning);
++counter;
}
m_guiContext->setFontColor(Vec4B::filled(255));
diff --git a/source/frontend/StarMerchantInterface.cpp b/source/frontend/StarMerchantInterface.cpp
index 7059cb8..4db2771 100644
--- a/source/frontend/StarMerchantInterface.cpp
+++ b/source/frontend/StarMerchantInterface.cpp
@@ -236,13 +236,13 @@ void MerchantPane::setupWidget(WidgetPtr const& widget, Json const& itemConfig)
String name = item->friendlyName();
if (item->count() > 1)
- name = strf("%s (x%s)", name, item->count());
+ name = strf("{} (x{})", name, item->count());
auto itemName = widget->fetchChild<LabelWidget>("itemName");
itemName->setText(name);
unsigned price = ceil(itemConfig.getInt("price", item->price()) * m_buyFactor);
- widget->setLabel("priceLabel", strf("%s", price));
+ widget->setLabel("priceLabel", strf("{}", price));
widget->setData(price);
bool unavailable = price > m_player->currency("money");
@@ -287,7 +287,7 @@ void MerchantPane::updateBuyTotal() {
else
m_buyTotal = 0;
- m_buyTotalLabel->setText(strf("%s", m_buyTotal));
+ m_buyTotalLabel->setText(strf("{}", m_buyTotal));
if (m_selectedIndex != NPos && m_buyCount > 0)
m_buyButton->enable();
@@ -332,7 +332,7 @@ void MerchantPane::updateSellTotal() {
if (item)
m_sellTotal += round(item->price() * m_sellFactor);
}
- m_sellTotalLabel->setText(strf("%s", m_sellTotal));
+ m_sellTotalLabel->setText(strf("{}", m_sellTotal));
if (m_sellTotal > 0)
m_sellButton->enable();
else
@@ -366,7 +366,7 @@ int MerchantPane::maxBuyCount() {
}
void MerchantPane::countChanged() {
- m_countTextBox->setText(strf("x%s", m_buyCount));
+ m_countTextBox->setText(strf("x{}", m_buyCount));
updateBuyTotal();
}
diff --git a/source/frontend/StarQuestInterface.cpp b/source/frontend/StarQuestInterface.cpp
index cb1f3e5..fa42b4d 100644
--- a/source/frontend/StarQuestInterface.cpp
+++ b/source/frontend/StarQuestInterface.cpp
@@ -236,7 +236,7 @@ void QuestLogInterface::fetchData() {
else if (filter.equalsIgnoreCase("completed"))
showQuests(m_manager->listCompletedQuests());
else
- throw StarException(strf("Unknown quest filter '%s'", filter));
+ throw StarException(strf("Unknown quest filter '{}'", filter));
}
void QuestLogInterface::showQuests(List<QuestPtr> quests) {
@@ -422,7 +422,7 @@ QuestCompleteInterface::QuestCompleteInterface(QuestPtr const& quest, PlayerPtr
commonSetup(config, m_quest->completionText(), "QuestComplete");
if (auto moneyLabel = fetchChild<LabelWidget>("lblMoneyAmount"))
- moneyLabel->setText(strf("%s", m_quest->money()));
+ moneyLabel->setText(strf("{}", m_quest->money()));
disableScissoring();
}
diff --git a/source/frontend/StarRadioMessagePopup.cpp b/source/frontend/StarRadioMessagePopup.cpp
index 6603dcf..f7c9061 100644
--- a/source/frontend/StarRadioMessagePopup.cpp
+++ b/source/frontend/StarRadioMessagePopup.cpp
@@ -51,7 +51,7 @@ void RadioMessagePopup::update() {
if (m_popupStage == PopupStage::AnimateIn) {
int frame = floor((1.0f - m_stageTimer.percent()) * m_animateInFrames);
- setBG("", strf("%s:%s", m_animateInImage, frame), "");
+ setBG("", strf("{}:{}", m_animateInImage, frame), "");
} else if (m_popupStage == PopupStage::ScrollText) {
int frame =
int((m_stageTimer.timer / m_message.portraitSpeed) * m_message.portraitFrames) % m_message.portraitFrames;
@@ -62,7 +62,7 @@ void RadioMessagePopup::update() {
// you're cool, just stay cool, cool person
} else if (m_popupStage == PopupStage::AnimateOut) {
int frame = floor((1.0f - m_stageTimer.percent()) * m_animateOutFrames);
- setBG("", strf("%s:%s", m_animateOutImage, frame), "");
+ setBG("", strf("{}:{}", m_animateOutImage, frame), "");
}
m_slideTimer = min(m_slideTimer + WorldTimestep, m_slideTime);
@@ -128,7 +128,7 @@ void RadioMessagePopup::enterStage(PopupStage newStage) {
if (m_popupStage == PopupStage::Hidden) {
m_portraitImage->hide();
m_messageLabel->hide();
- setBG("", strf("%s:0", m_animateInImage), "");
+ setBG("", strf("{}:0", m_animateInImage), "");
} else if (m_popupStage == PopupStage::AnimateIn) {
m_stageTimer = GameTimer(m_animateInTime);
m_portraitImage->hide();
diff --git a/source/frontend/StarScriptPane.cpp b/source/frontend/StarScriptPane.cpp
index 87c1353..e2e8a33 100644
--- a/source/frontend/StarScriptPane.cpp
+++ b/source/frontend/StarScriptPane.cpp
@@ -179,7 +179,7 @@ LuaCallbacks ScriptPane::makePaneCallbacks() {
});
callbacks.registerCallback("addWidget", [this](Json const& newWidgetConfig, Maybe<String> const& newWidgetName) {
- String name = newWidgetName.value(strf("%d", Random::randu64()));
+ String name = newWidgetName.value(strf("{}", Random::randu64()));
WidgetPtr newWidget = m_reader.makeSingle(name, newWidgetConfig);
this->addChild(name, newWidget);
});
diff --git a/source/frontend/StarTeamBar.cpp b/source/frontend/StarTeamBar.cpp
index 48a9b51..6091d9c 100644
--- a/source/frontend/StarTeamBar.cpp
+++ b/source/frontend/StarTeamBar.cpp
@@ -159,7 +159,7 @@ void TeamBar::buildTeamBar() {
continue;
}
- String cellName = strf("%s", controlIndex);
+ String cellName = strf("{}", controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell) {
@@ -231,7 +231,7 @@ void TeamBar::buildTeamBar() {
noInviteImage->setVisibility(!couldInvite);
while (true) {
- String cellName = strf("%s", controlIndex);
+ String cellName = strf("{}", controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell)
break;
diff --git a/source/frontend/StarTeleportDialog.cpp b/source/frontend/StarTeleportDialog.cpp
index eef6250..76f0310 100644
--- a/source/frontend/StarTeleportDialog.cpp
+++ b/source/frontend/StarTeleportDialog.cpp
@@ -57,7 +57,7 @@ TeleportDialog::TeleportDialog(UniverseClientPtr client,
entry->fetchChild<LabelWidget>("planetName")->setText(dest.getString("planetName", ""));
if (dest.contains("icon"))
entry->fetchChild<ImageWidget>("icon")->setImage(
- strf("/interface/bookmarks/icons/%s.png", dest.getString("icon")));
+ strf("/interface/bookmarks/icons/{}.png", dest.getString("icon")));
entry->fetchChild<ButtonWidget>("editButton")->hide();
if (dest.getBool("mission", false)) {
diff --git a/source/frontend/StarWidgetLuaBindings.cpp b/source/frontend/StarWidgetLuaBindings.cpp
index 1029daa..eb3ff5b 100644
--- a/source/frontend/StarWidgetLuaBindings.cpp
+++ b/source/frontend/StarWidgetLuaBindings.cpp
@@ -180,7 +180,7 @@ LuaCallbacks LuaBindings::makeWidgetCallbacks(Widget* parentWidget, GuiReader* r
callbacks.registerCallback("addChild", [parentWidget, reader](String const& widgetName, Json const& newChildConfig, Maybe<String> const& newChildName) {
if (auto widget = parentWidget->fetchChild<Widget>(widgetName)) {
- String name = newChildName.value(strf("%d", Random::randu64()));
+ String name = newChildName.value(strf("{}", Random::randu64()));
WidgetPtr newChild = reader->makeSingle(name, newChildConfig);
widget->addChild(name, newChild);
}
diff --git a/source/game/StarActorMovementController.cpp b/source/game/StarActorMovementController.cpp
index d4266eb..1b8f0e4 100644
--- a/source/game/StarActorMovementController.cpp
+++ b/source/game/StarActorMovementController.cpp
@@ -1084,10 +1084,10 @@ void ActorMovementController::doSetAnchorState(Maybe<EntityAnchorState> anchorSt
if (anchorState) {
auto anchorableEntity = as<AnchorableEntity>(world()->entity(anchorState->entityId));
if (!anchorableEntity)
- throw ActorMovementControllerException::format("No such anchorable entity id %s in ActorMovementController::setAnchorState", anchorState->entityId);
+ throw ActorMovementControllerException::format("No such anchorable entity id {} in ActorMovementController::setAnchorState", anchorState->entityId);
entityAnchor = anchorableEntity->anchor(anchorState->positionIndex);
if (!entityAnchor)
- throw ActorMovementControllerException::format("Anchor position %s is disabled ActorMovementController::setAnchorState", anchorState->positionIndex);
+ throw ActorMovementControllerException::format("Anchor position {} is disabled ActorMovementController::setAnchorState", anchorState->positionIndex);
}
if (!entityAnchor && m_entityAnchor && m_entityAnchor->exitBottomPosition) {
@@ -1327,7 +1327,7 @@ Maybe<bool> PathController::move(ActorMovementController& movementController, Ac
m_edgeIndex++;
if (m_edgeIndex < m_path->size()) {
if (!validateEdge(movementController, m_path->at(m_edgeIndex))) {
- // Logger::info("Path invalidated on %s %s %s", ActionNames.getRight(nextEdge.action), nextEdge.source.position, nextEdge.target.position);
+ // Logger::info("Path invalidated on {} {} {}", ActionNames.getRight(nextEdge.action), nextEdge.source.position, nextEdge.target.position);
reset();
return {};
}
@@ -1351,7 +1351,7 @@ Maybe<bool> PathController::move(ActorMovementController& movementController, Ac
// Vec2F velocity = debugEdge.source.velocity.orMaybe(debugEdge.target.velocity).value({ 0.0, 0.0 });
// SpatialLogger::logPoint("world", debugEdge.source.position, Color::Yellow.toRgba());
// SpatialLogger::logLine("world", debugEdge.source.position, debugEdge.target.position, Color::Yellow.toRgba());
- // SpatialLogger::logText("world", strf("%s %s", ActionNames.getRight(debugEdge.action), curVelocity), debugEdge.source.position, Color::Yellow.toRgba());
+ // SpatialLogger::logText("world", strf("{} {}", ActionNames.getRight(debugEdge.action), curVelocity), debugEdge.source.position, Color::Yellow.toRgba());
// }
// }
diff --git a/source/game/StarAiDatabase.cpp b/source/game/StarAiDatabase.cpp
index fef184b..8058a24 100644
--- a/source/game/StarAiDatabase.cpp
+++ b/source/game/StarAiDatabase.cpp
@@ -62,7 +62,7 @@ AiSpeech AiDatabase::noMissionsSpeech() const {
}
String AiDatabase::portraitImage(String const& species, String const& frame) const {
- return strf("/ai/%s:%s", m_speciesParameters.get(species).portraitFrames, frame);
+ return strf("/ai/{}:{}", m_speciesParameters.get(species).portraitFrames, frame);
}
Animation AiDatabase::animation(String const& species, String const& animationName) const {
diff --git a/source/game/StarBehaviorDatabase.cpp b/source/game/StarBehaviorDatabase.cpp
index 4306cd7..5e08d98 100644
--- a/source/game/StarBehaviorDatabase.cpp
+++ b/source/game/StarBehaviorDatabase.cpp
@@ -92,7 +92,7 @@ NodeParameterValue replaceBehaviorTag(NodeParameterValue const& parameter, Strin
if (auto replace = treeParameters.maybe(treeKey)) {
return *replace;
} else {
- throw StarException(strf("No parameter specified for tag '%s'", key));
+ throw StarException(strf("No parameter specified for tag '{}'", key));
}
}
}
@@ -110,7 +110,7 @@ Maybe<String> replaceOutputBehaviorTag(Maybe<String> const& output, StringMap<No
else
return {};
} else {
- throw StarException(strf("No parameter specified for tag '%s'", *out));
+ throw StarException(strf("No parameter specified for tag '{}'", *out));
}
}
}
@@ -170,7 +170,7 @@ BehaviorDatabase::BehaviorDatabase() {
m_nodeOutput.set(node.first, output);
}
} catch (StarException const& e) {
- throw StarException(strf("Could not load nodes file \'%s\'", file), e);
+ throw StarException(strf("Could not load nodes file \'{}\'", file), e);
}
}
@@ -182,11 +182,11 @@ BehaviorDatabase::BehaviorDatabase() {
auto name = config.getString("name");
if (m_configs.contains(name))
- throw StarException(strf("Duplicate behavior tree \'%s\'", name));
+ throw StarException(strf("Duplicate behavior tree \'{}\'", name));
m_configs[name] = config;
} catch (StarException const& e) {
- throw StarException(strf("Could not load behavior file \'%s\'", file), e);
+ throw StarException(strf("Could not load behavior file \'{}\'", file), e);
}
}
@@ -198,7 +198,7 @@ BehaviorDatabase::BehaviorDatabase() {
BehaviorTreeConstPtr BehaviorDatabase::behaviorTree(String const& name) const {
if (!m_behaviors.contains(name))
- throw StarException(strf("No such behavior tree \'%s\'", name));
+ throw StarException(strf("No such behavior tree \'{}\'", name));
return m_behaviors.get(name);
}
@@ -219,7 +219,7 @@ BehaviorTreeConstPtr BehaviorDatabase::buildTree(Json const& config, StringMap<N
Json BehaviorDatabase::behaviorConfig(String const& name) const {
if (!m_configs.contains(name))
- throw StarException(strf("No such behavior tree \'%s\'", name));
+ throw StarException(strf("No such behavior tree \'{}\'", name));
return m_configs.get(name);
}
@@ -246,7 +246,7 @@ CompositeNode BehaviorDatabase::compositeNode(Json const& config, StringMap<Node
return RandomizeNode(children);
// above statement needs to be exhaustive
- throw StarException(strf("Composite node type '%s' could not be created from JSON", CompositeTypeNames.getRight(type)));
+ throw StarException(strf("Composite node type '{}' could not be created from JSON", CompositeTypeNames.getRight(type)));
}
BehaviorNodeConstPtr BehaviorDatabase::behaviorNode(Json const& json, StringMap<NodeParameterValue> const& treeParameters, BehaviorTree& tree) const {
@@ -292,7 +292,7 @@ BehaviorNodeConstPtr BehaviorDatabase::behaviorNode(Json const& json, StringMap<
}
// above statement must be exhaustive
- throw StarException(strf("Behavior node type '%s' could not be created from JSON", BehaviorNodeTypeNames.getRight(type)));
+ throw StarException(strf("Behavior node type '{}' could not be created from JSON", BehaviorNodeTypeNames.getRight(type)));
}
}
diff --git a/source/game/StarBehaviorState.cpp b/source/game/StarBehaviorState.cpp
index 5308f3a..39a800e 100644
--- a/source/game/StarBehaviorState.cpp
+++ b/source/game/StarBehaviorState.cpp
@@ -67,7 +67,7 @@ LuaTable Blackboard::parameters(StringMap<NodeParameter> const& parameters, uint
// dumb special case for allowing a vec2 of blackboard number keys
if (p.second.first == NodeParameterType::Vec2) {
if (value.type() != Json::Type::Array)
- throw StarException(strf("Vec2 parameter not of array type for key %s", p.first, value));
+ throw StarException(strf("Vec2 parameter not of array type for key {}", p.first, value));
JsonArray vector = value.toArray();
LuaTable luaVector = m_luaContext.engine().createTable();
for (int i = 0; i < 2; i++) {
@@ -210,7 +210,7 @@ NodeStatus BehaviorState::runAction(ActionNode const& node, NodeState& state) {
try {
result = thread.resume<ActionReturn>(parameters, blackboardPtr(), id, m_lastDt).value(ActionReturn(NodeStatus::Invalid, LuaNil));
} catch (LuaException const& e) {
- throw StarException(strf("Lua Exception caught running action node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
+ throw StarException(strf("Lua Exception caught running action node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
auto status = get<0>(result);
@@ -222,7 +222,7 @@ NodeStatus BehaviorState::runAction(ActionNode const& node, NodeState& state) {
try {
result = thread.resume<ActionReturn>(m_lastDt).value(ActionReturn(NodeStatus::Invalid, LuaNil));
} catch (LuaException const& e) {
- throw StarException(strf("Lua Exception caught resuming action node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
+ throw StarException(strf("Lua Exception caught resuming action node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
auto status = get<0>(result);
@@ -246,7 +246,7 @@ NodeStatus BehaviorState::runDecorator(DecoratorNode const& node, NodeState& sta
try {
status = thread.resume<NodeStatus>(parameters, blackboardPtr(), id).value(NodeStatus::Invalid);
} catch (LuaException const& e) {
- throw StarException(strf("Lua Exception caught initializing decorator node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
+ throw StarException(strf("Lua Exception caught initializing decorator node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
if (status == NodeStatus::Success || status == NodeStatus::Failure)
return status;
@@ -262,7 +262,7 @@ NodeStatus BehaviorState::runDecorator(DecoratorNode const& node, NodeState& sta
try {
status = decorator.thread.resume<NodeStatus>(childStatus).value(NodeStatus::Invalid);
} catch (LuaException const& e) {
- throw StarException(strf("Lua Exception caught resuming decorator node %s in behavior %s: %s", node.name, m_tree->name, outputException(e, false)));
+ throw StarException(strf("Lua Exception caught resuming decorator node {} in behavior {}: {}", node.name, m_tree->name, outputException(e, false)));
}
} else {
return NodeStatus::Running;
@@ -287,7 +287,7 @@ NodeStatus BehaviorState::runComposite(CompositeNode const& node, NodeState& sta
else if (node.is<RandomizeNode>())
status = runRandomize(node.get<RandomizeNode>(), state);
else
- throw StarException(strf("Unable to run composite node type with variant type index %s", node.typeIndex()));
+ throw StarException(strf("Unable to run composite node type with variant type index {}", node.typeIndex()));
return status;
}
diff --git a/source/game/StarBiomeDatabase.cpp b/source/game/StarBiomeDatabase.cpp
index d797a56..9a39781 100644
--- a/source/game/StarBiomeDatabase.cpp
+++ b/source/game/StarBiomeDatabase.cpp
@@ -24,7 +24,7 @@ BiomeDatabase::BiomeDatabase() {
auto name = parameters.getString("name");
if (map.contains(name))
- throw BiomeException(strf("Duplicate %s generator name '%s'", type, name));
+ throw BiomeException(strf("Duplicate {} generator name '{}'", type, name));
map[name] = {path, name, parameters};
}
};
@@ -125,20 +125,20 @@ StringList BiomeDatabase::weatherNames() const {
WeatherType BiomeDatabase::weatherType(String const& name) const {
if (!m_weathers.contains(name))
- throw BiomeException(strf("No such weather type '%s'", name));
+ throw BiomeException(strf("No such weather type '{}'", name));
auto config = m_weathers.get(name);
try {
return WeatherType(config.parameters, config.path);
} catch (MapException const& e) {
- throw BiomeException(strf("Required key not found in weather config %s", config.path), e);
+ throw BiomeException(strf("Required key not found in weather config {}", config.path), e);
}
}
BiomePtr BiomeDatabase::createBiome(String const& biomeName, uint64_t seed, float verticalMidPoint, float threatLevel) const {
if (!m_biomes.contains(biomeName))
- throw BiomeException(strf("No such biome '%s'", biomeName));
+ throw BiomeException(strf("No such biome '{}'", biomeName));
auto& root = Root::singleton();
auto materialDatabase = root.materialDatabase();
@@ -183,7 +183,7 @@ BiomePtr BiomeDatabase::createBiome(String const& biomeName, uint64_t seed, floa
return biome;
} catch (std::exception const& cause) {
- throw BiomeException(strf("Failed to parse biome: '%s'", biomeName), cause);
+ throw BiomeException(strf("Failed to parse biome: '{}'", biomeName), cause);
}
}
diff --git a/source/game/StarBiomePlacement.cpp b/source/game/StarBiomePlacement.cpp
index 50786a8..a7c2802 100644
--- a/source/game/StarBiomePlacement.cpp
+++ b/source/game/StarBiomePlacement.cpp
@@ -23,7 +23,7 @@ BiomeItem variantToBiomeItem(Json const& store) {
} else if (type == "microDungeon") {
return MicroDungeonNames(jsonToStringSet(store.get(1)));
} else {
- throw BiomeException(strf("Unrecognized biome item type '%s'", type));
+ throw BiomeException(strf("Unrecognized biome item type '{}'", type));
}
}
@@ -138,7 +138,7 @@ Maybe<BiomeItem> BiomeItemDistribution::createItem(Json const& config, RandomSou
return BiomeItem{MicroDungeonNames(jsonToStringSet(config.get("microdungeons", JsonArray())))};
} else {
- throw BiomeException(strf("No such item type '%s' in item distribution", type));
+ throw BiomeException(strf("No such item type '{}' in item distribution", type));
}
return {};
diff --git a/source/game/StarCelestialCoordinate.cpp b/source/game/StarCelestialCoordinate.cpp
index 3652718..70bd61d 100644
--- a/source/game/StarCelestialCoordinate.cpp
+++ b/source/game/StarCelestialCoordinate.cpp
@@ -31,11 +31,11 @@ CelestialCoordinate::CelestialCoordinate(Json const& variant) : CelestialCoordin
m_satelliteOrbitNumber = lexicalCast<int>(plist.at(4));
if (m_planetaryOrbitNumber <= 0)
- throw CelestialException(strf("Planetary body number out of range in '%s'", id));
+ throw CelestialException(strf("Planetary body number out of range in '{}'", id));
if (m_satelliteOrbitNumber < 0)
- throw CelestialException(strf("Satellite body number out of range in '%s'", id));
+ throw CelestialException(strf("Satellite body number out of range in '{}'", id));
} catch (StarException const& e) {
- throw CelestialException(strf("Error parsing CelestialCoordinate from '%s'", id), e);
+ throw CelestialException(strf("Error parsing CelestialCoordinate from '{}'", id), e);
}
}
} else if (variant.isType(Json::Type::Object)) {
@@ -44,7 +44,7 @@ CelestialCoordinate::CelestialCoordinate(Json const& variant) : CelestialCoordin
m_satelliteOrbitNumber = variant.getInt("satellite", 0);
} else if (!variant.isNull()) {
throw CelestialException(
- strf("Improper variant type %s trying to convert to SystemCoordinate", variant.typeName()));
+ strf("Improper variant type {} trying to convert to SystemCoordinate", variant.typeName()));
}
}
@@ -153,12 +153,12 @@ std::ostream& operator<<(std::ostream& os, CelestialCoordinate const& coord) {
if (coord.isNull()) {
os << "null";
} else {
- format(os, "%s:%s:%s", coord.m_location[0], coord.m_location[1], coord.m_location[2]);
+ format(os, "{}:{}:{}", coord.m_location[0], coord.m_location[1], coord.m_location[2]);
if (coord.m_planetaryOrbitNumber) {
- format(os, ":%s", coord.m_planetaryOrbitNumber);
+ format(os, ":{}", coord.m_planetaryOrbitNumber);
if (coord.m_satelliteOrbitNumber)
- format(os, ":%s", coord.m_satelliteOrbitNumber);
+ format(os, ":{}", coord.m_satelliteOrbitNumber);
}
}
diff --git a/source/game/StarCelestialDatabase.cpp b/source/game/StarCelestialDatabase.cpp
index 718bfde..f2a70d0 100644
--- a/source/game/StarCelestialDatabase.cpp
+++ b/source/game/StarCelestialDatabase.cpp
@@ -138,7 +138,7 @@ CelestialMasterDatabase::CelestialMasterDatabase(Maybe<String> databaseFile) {
if (m_database.contentIdentifier() != "Celestial2") {
Logger::error("CelestialMasterDatabase database content identifier is not 'Celestial2', moving out of the way and recreating");
m_database.close();
- File::rename(*databaseFile, strf("%s.%s.fail", *databaseFile, Time::millisecondsSinceEpoch()));
+ File::rename(*databaseFile, strf("{}.{}.fail", *databaseFile, Time::millisecondsSinceEpoch()));
m_database.setIODevice(File::open(*databaseFile, IOMode::ReadWrite));
m_database.open();
}
@@ -453,12 +453,12 @@ Maybe<pair<CelestialParameters, HashMap<int, CelestialPlanet>>> CelestialMasterD
String mid = m_generationInformation.systemNames.select(random);
String suffix = m_generationInformation.systemSuffixNames.select(random);
- String systemName = String(strf("%s %s %s", prefix, mid, suffix)).trim();
+ String systemName = String(strf("{} {} {}", prefix, mid, suffix)).trim();
- systemName = systemName.replace("<onedigit>", strf("%01d", random.randu32() % 10));
- systemName = systemName.replace("<twodigit>", strf("%02d", random.randu32() % 100));
- systemName = systemName.replace("<threedigit>", strf("%03d", random.randu32() % 1000));
- systemName = systemName.replace("<fourdigit>", strf("%04d", random.randu32() % 10000));
+ systemName = systemName.replace("<onedigit>", strf("{:01d}", random.randu32() % 10));
+ systemName = systemName.replace("<twodigit>", strf("{:02d}", random.randu32() % 100));
+ systemName = systemName.replace("<threedigit>", strf("{:03d}", random.randu32() % 1000));
+ systemName = systemName.replace("<fourdigit>", strf("{:04d}", random.randu32() % 10000));
CelestialParameters systemParameters = CelestialParameters(systemCoordinate,
systemSeed,
@@ -485,7 +485,7 @@ Maybe<pair<CelestialParameters, HashMap<int, CelestialPlanet>>> CelestialMasterD
CelestialCoordinate planetCoordinate(location, planetPair.first);
uint64_t planetarySeed = random.randu64();
- String planetaryName = strf("%s %s", systemName, m_generationInformation.planetarySuffixes.at(planetPair.second));
+ String planetaryName = strf("{} {}", systemName, m_generationInformation.planetarySuffixes.at(planetPair.second));
CelestialPlanet planet;
planet.planetParameters =
@@ -510,7 +510,7 @@ Maybe<pair<CelestialParameters, HashMap<int, CelestialPlanet>>> CelestialMasterD
CelestialCoordinate satelliteCoordinate(location, planetPair.first, satellitePair.first);
uint64_t satelliteSeed = random.randu64();
String satelliteName =
- strf("%s %s", planetaryName, m_generationInformation.satelliteSuffixes.at(satellitePair.second));
+ strf("{} {}", planetaryName, m_generationInformation.satelliteSuffixes.at(satellitePair.second));
planet.satelliteParameters[satellitePair.first] =
CelestialParameters(satelliteCoordinate, satelliteSeed, satelliteName, satelliteParameters);
diff --git a/source/game/StarCelestialGraphics.cpp b/source/game/StarCelestialGraphics.cpp
index 3e0c02e..e1a5aa8 100644
--- a/source/game/StarCelestialGraphics.cpp
+++ b/source/game/StarCelestialGraphics.cpp
@@ -55,7 +55,7 @@ List<pair<String, float>> CelestialGraphics::drawWorld(
layers.append({move(liquidBaseImage), imageScale});
} else {
if (baseCount > 0) {
- String baseLayer = strf("%s?hueshift=%s", baseImages.replace("<biome>",
+ String baseLayer = strf("{}?hueshift={}", baseImages.replace("<biome>",
terrestrialParameters->primaryBiome).replace("<num>", toString(baseCount)), terrestrialParameters->hueShift);
layers.append({move(baseLayer), imageScale});
}
@@ -68,7 +68,7 @@ List<pair<String, float>> CelestialGraphics::drawWorld(
if (!dynamicsImages.empty())
dynamicMaskString = "?addmask=" + dynamicsImages.replace("<num>", toString(celestialParameters.randomizeParameterRange(gfxConfig.getArray("dynamicsRange"), i).toInt()));
if (terrestrialParameters->hueShift != 0)
- hueShiftString = strf("?hueshift=%s", terrestrialParameters->hueShift);
+ hueShiftString = strf("?hueshift={}", terrestrialParameters->hueShift);
String layer = baseImage + hueShiftString + dynamicMaskString;
layers.append({move(layer), imageScale});
}
@@ -87,7 +87,7 @@ List<pair<String, float>> CelestialGraphics::drawWorld(
for (int i = 0; i < maskCount; ++i) {
String biomeMaskBase = maskImages.replace("<num>", toString(maskCount - i));
String dynamicMask = dynamicsImages.replace("<num>", toString(celestialParameters.randomizeParameterRange("dynamicsRange", i).toInt()));
- String layer = strf("%s?addmask=%s", biomeMaskBase, dynamicMask);
+ String layer = strf("{}?addmask={}", biomeMaskBase, dynamicMask);
layers.append({move(layer), imageScale});
}
@@ -114,14 +114,14 @@ List<pair<String, float>> CelestialGraphics::drawWorld(
float hueShift = celestialParameters.randomizeParameterRange(gfxConfig.getArray("primaryHueShiftRange")).toFloat();
if (!baseImage.empty())
- layers.append({strf("%s?hueshift=%s", baseImage, hueShift), imageScale});
+ layers.append({strf("{}?hueshift={}", baseImage, hueShift), imageScale});
if (!overlayImages.empty()) {
for (int i = 0; i < overlayCount; ++i) {
hueShift += celestialParameters.randomizeParameterRange(gfxConfig.getArray("hueShiftOffsetRange")).toFloat();
String maskImage = dynamicsImages.replace("<num>", toString(celestialParameters.randomizeParameterRange(gfxConfig.getArray("dynamicsRange"), i).toInt()));
String overlayImage = overlayImages.replace("<num>", toString(i));
- layers.append({strf("%s?hueshift=%s?addmask=%s", overlayImage, hueShift, maskImage), imageScale});
+ layers.append({strf("{}?hueshift={}?addmask={}", overlayImage, hueShift, maskImage), imageScale});
}
}
@@ -245,7 +245,7 @@ List<pair<String, float>> CelestialGraphics::drawSystemTwinkle(CelestialDatabase
float twinkleTime = parameters->randomizeParameterRange("twinkleTime").toFloat();
String twinkleBackground = parameters->getParameter("twinkleBackground").toString();
- String twinkleFrame = strf("%s:%s", twinkleFrameset, (int)(std::fmod<double>(time / twinkleTime, 1.0f) * twinkleFrameCount));
+ String twinkleFrame = strf("{}:{}", twinkleFrameset, (int)(std::fmod<double>(time / twinkleTime, 1.0f) * twinkleFrameCount));
return {{move(twinkleBackground), 1.0f}, {move(twinkleFrame), twinkleScale}};
}
diff --git a/source/game/StarCelestialParameters.cpp b/source/game/StarCelestialParameters.cpp
index c637e43..9f94c4c 100644
--- a/source/game/StarCelestialParameters.cpp
+++ b/source/game/StarCelestialParameters.cpp
@@ -97,7 +97,7 @@ Json CelestialParameters::randomizeParameterRange(String const& name, int32_t mi
JsonArray list = parameter.toArray();
if (list.size() != 2)
throw CelestialException(
- strf("Parameter '%s' does not appear to be a range in CelestialParameters::randomizeRange", name));
+ strf("Parameter '{}' does not appear to be a range in CelestialParameters::randomizeRange", name));
return randomizeParameterRange(list, mix, name);
}
diff --git a/source/game/StarChatProcessor.cpp b/source/game/StarChatProcessor.cpp
index c298e13..2082529 100644
--- a/source/game/StarChatProcessor.cpp
+++ b/source/game/StarChatProcessor.cpp
@@ -8,7 +8,7 @@ String ChatProcessor::connectClient(ConnectionId clientId, String nick) {
RecursiveMutexLocker locker(m_mutex);
if (nick.empty())
- nick = strf("Player_%s", clientId);
+ nick = strf("Player_{}", clientId);
nick = makeNickUnique(nick);
@@ -17,7 +17,7 @@ String ChatProcessor::connectClient(ConnectionId clientId, String nick) {
{MessageContext::Broadcast},
ServerConnectionId,
ServerNick,
- strf("Player '%s' connected", nick)
+ strf("Player '{}' connected", nick)
});
}
@@ -41,7 +41,7 @@ List<ChatReceivedMessage> ChatProcessor::disconnectClient(ConnectionId clientId)
{MessageContext::Broadcast},
ServerConnectionId,
ServerNick,
- strf("Player '%s' disconnected", clientInfo.nick)
+ strf("Player '{}' disconnected", clientInfo.nick)
});
}
@@ -229,17 +229,17 @@ bool ChatProcessor::handleCommand(ChatReceivedMessage& message) {
if (command == "nick") {
auto newNick = renick(message.fromConnection, commandLine.trim());
- response = strf("Nick changed to %s", newNick);
+ response = strf("Nick changed to {}", newNick);
} else if (command == "w") {
String target = commandLine.extract();
if (m_nicks.contains(target))
whisper(message.fromConnection, m_nicks.get(target), commandLine.trim());
else
- response = strf("No such nick %s", target);
+ response = strf("No such nick {}", target);
} else if (m_commandHandler) {
response = m_commandHandler(message.fromConnection, command, commandLine);
} else {
- response = strf("No such command %s", command);
+ response = strf("No such command {}", command);
}
if (!response.empty()) {
diff --git a/source/game/StarCodexDatabase.cpp b/source/game/StarCodexDatabase.cpp
index e3ef2ff..c7e8972 100644
--- a/source/game/StarCodexDatabase.cpp
+++ b/source/game/StarCodexDatabase.cpp
@@ -19,11 +19,11 @@ CodexDatabase::CodexDatabase() {
auto codex = make_shared<Codex>(codexJson, AssetPath::directory(file));
if (m_codexes.contains(codex->id()))
- throw CodexDatabaseException::format("Duplicate codex named '%s', config file '%s'", codex->id(), file);
+ throw CodexDatabaseException::format("Duplicate codex named '{}', config file '{}'", codex->id(), file);
m_codexes[codex->id()] = codex;
} catch (std::exception const& e) {
- throw CodexDatabaseException(strf("Error reading codex config %s", file), e);
+ throw CodexDatabaseException(strf("Error reading codex config {}", file), e);
}
}
}
diff --git a/source/game/StarCollectionDatabase.cpp b/source/game/StarCollectionDatabase.cpp
index c407278..d8d573d 100644
--- a/source/game/StarCollectionDatabase.cpp
+++ b/source/game/StarCollectionDatabase.cpp
@@ -59,7 +59,7 @@ Collection CollectionDatabase::collection(String const& collectionName) const {
try {
return m_collections.get(collectionName);
} catch (MapException const& e) {
- throw CollectionDatabaseException(strf("Collection '%s' not found", collectionName), e);
+ throw CollectionDatabaseException(strf("Collection '{}' not found", collectionName), e);
}
}
@@ -67,7 +67,7 @@ List<Collectable> CollectionDatabase::collectables(String const& collectionName)
try {
return m_collectables.get(collectionName).values();
} catch (MapException const& e) {
- throw CollectionDatabaseException(strf("Collection '%s' not found", collectionName), e);
+ throw CollectionDatabaseException(strf("Collection '{}' not found", collectionName), e);
}
}
@@ -75,7 +75,7 @@ Collectable CollectionDatabase::collectable(String const& collectionName, String
try {
return m_collectables.get(collectionName).get(collectableName);
} catch (MapException const& e) {
- throw CollectionDatabaseException(strf("Collectable '%s' not found in collection '%s'", collectableName, collectionName), e);
+ throw CollectionDatabaseException(strf("Collectable '{}' not found in collection '{}'", collectableName, collectionName), e);
}
}
diff --git a/source/game/StarCommandProcessor.cpp b/source/game/StarCommandProcessor.cpp
index ae7a913..0c7a8c8 100644
--- a/source/game/StarCommandProcessor.cpp
+++ b/source/game/StarCommandProcessor.cpp
@@ -98,9 +98,9 @@ String CommandProcessor::admin(ConnectionId connectionId, String const&) {
m_universe->setAdmin(connectionId, !wasAdmin);
if (!wasAdmin)
- return strf("Admin privileges now given to player %s", m_universe->clientNick(connectionId));
+ return strf("Admin privileges now given to player {}", m_universe->clientNick(connectionId));
else
- return strf("Admin privileges taken away from %s", m_universe->clientNick(connectionId));
+ return strf("Admin privileges taken away from {}", m_universe->clientNick(connectionId));
} else {
return "Insufficient privileges to make self admin.";
}
@@ -110,11 +110,11 @@ String CommandProcessor::pvp(ConnectionId connectionId, String const&) {
if (!m_universe->isPvp(connectionId)) {
m_universe->setPvp(connectionId, true);
if (m_universe->isPvp(connectionId))
- m_universe->adminBroadcast(strf("Player %s is now PVP", m_universe->clientNick(connectionId)));
+ m_universe->adminBroadcast(strf("Player {} is now PVP", m_universe->clientNick(connectionId)));
} else {
m_universe->setPvp(connectionId, false);
if (!m_universe->isPvp(connectionId))
- m_universe->adminBroadcast(strf("Player %s is a big wimp and is no longer PVP", m_universe->clientNick(connectionId)));
+ m_universe->adminBroadcast(strf("Player {} is a big wimp and is no longer PVP", m_universe->clientNick(connectionId)));
}
if (m_universe->isPvp(connectionId))
@@ -124,7 +124,7 @@ String CommandProcessor::pvp(ConnectionId connectionId, String const&) {
}
String CommandProcessor::whoami(ConnectionId connectionId, String const&) {
- return strf("Server: You are %s. You are %san Admin",
+ return strf("Server: You are {}. You are {}an Admin",
m_universe->clientNick(connectionId),
m_universe->isAdmin(connectionId) ? "" : "not ");
}
@@ -137,8 +137,8 @@ String CommandProcessor::warp(ConnectionId connectionId, String const& argumentS
m_universe->clientWarpPlayer(connectionId, parseWarpAction(argumentString));
return "Lets do the space warp again";
} catch (StarException const& e) {
- Logger::warn("Could not parse warp target: %s", outputException(e, false));
- return strf("Could not parse the argument %s as a warp target", argumentString);
+ Logger::warn("Could not parse warp target: {}", outputException(e, false));
+ return strf("Could not parse the argument {} as a warp target", argumentString);
}
}
@@ -188,7 +188,7 @@ String CommandProcessor::warpRandom(ConnectionId connectionId, String const& typ
}
m_universe->clientWarpPlayer(connectionId, WarpToWorld(CelestialWorldId(*target)));
- return strf("warping to %s", *target);
+ return strf("warping to {}", *target);
}
String CommandProcessor::timewarp(ConnectionId connectionId, String const& argumentString) {
@@ -203,7 +203,7 @@ String CommandProcessor::timewarp(ConnectionId connectionId, String const& argum
m_universe->universeClock()->adjustTime(time);
return "It's just a jump to the left...";
} catch (BadLexicalCast const&) {
- return strf("Could not parse the argument %s as a time adjustment", argumentString);
+ return strf("Could not parse the argument {} as a time adjustment", argumentString);
}
}
@@ -299,17 +299,17 @@ String CommandProcessor::spawnItem(ConnectionId connectionId, String const& argu
return done ? "" : "Invalid client state";
} catch (JsonParsingException const& exception) {
- Logger::warn("Error while processing /spawnitem '%s' command. Json parse problem: %s", arguments.at(0), outputException(exception, false));
+ Logger::warn("Error while processing /spawnitem '{}' command. Json parse problem: {}", arguments.at(0), outputException(exception, false));
return "Could not parse item parameters";
} catch (ItemException const& exception) {
- Logger::warn("Error while processing /spawnitem '%s' command. Item instantiation problem: %s", arguments.at(0), outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawnitem '{}' command. Item instantiation problem: {}", arguments.at(0), outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
} catch (BadLexicalCast const& exception) {
- Logger::warn("Error while processing /spawnitem command. Number expected. Got something else: %s", outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawnitem command. Number expected. Got something else: {}", outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
} catch (StarException const& exception) {
- Logger::warn("Error while processing /spawnitem command '%s', exception caught: %s", argumentString, outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawnitem command '{}', exception caught: {}", argumentString, outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
}
}
@@ -337,17 +337,17 @@ String CommandProcessor::spawnTreasure(ConnectionId connectionId, String const&
return done ? "" : "Invalid client state";
} catch (JsonParsingException const& exception) {
- Logger::warn("Error while processing /spawntreasure '%s' command. Json parse problem: %s", arguments.at(0), outputException(exception, false));
+ Logger::warn("Error while processing /spawntreasure '{}' command. Json parse problem: {}", arguments.at(0), outputException(exception, false));
return "Could not parse item parameters";
} catch (ItemException const& exception) {
- Logger::warn("Error while processing /spawntreasure '%s' command. Item instantiation problem: %s", arguments.at(0), outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawntreasure '{}' command. Item instantiation problem: {}", arguments.at(0), outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
} catch (BadLexicalCast const& exception) {
- Logger::warn("Error while processing /spawntreasure command. Number expected. Got something else: %s", outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawntreasure command. Number expected. Got something else: {}", outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
} catch (StarException const& exception) {
- Logger::warn("Error while processing /spawntreasure command '%s', exception caught: %s", argumentString, outputException(exception, false));
- return strf("Could not load item '%s'", arguments.at(0));
+ Logger::warn("Error while processing /spawntreasure command '{}', exception caught: {}", argumentString, outputException(exception, false));
+ return strf("Could not load item '{}'", arguments.at(0));
}
}
@@ -378,8 +378,8 @@ String CommandProcessor::spawnMonster(ConnectionId connectionId, String const& a
return done ? "" : "Invalid client state";
} catch (StarException const& exception) {
- Logger::warn("Could not spawn Monster of type '%s', exception caught: %s", argumentString, outputException(exception, false));
- return strf("Could not spawn Monster of type '%s'", argumentString);
+ Logger::warn("Could not spawn Monster of type '{}', exception caught: {}", argumentString, outputException(exception, false));
+ return strf("Could not spawn Monster of type '{}'", argumentString);
}
}
@@ -413,8 +413,8 @@ String CommandProcessor::spawnNpc(ConnectionId connectionId, String const& argum
return done ? "" : "Invalid client state";
} catch (StarException const& exception) {
- Logger::warn("Could not spawn NPC of species '%s', exception caught: %s", argumentString, outputException(exception, true));
- return strf("Could not spawn NPC of species '%s'", argumentString);
+ Logger::warn("Could not spawn NPC of species '{}', exception caught: {}", argumentString, outputException(exception, true));
+ return strf("Could not spawn NPC of species '{}'", argumentString);
}
}
@@ -443,7 +443,7 @@ String CommandProcessor::spawnVehicle(ConnectionId connectionId, String const& a
return done ? "" : "Invalid client state";
} catch (StarException const& exception) {
- Logger::warn("Could not spawn vehicle, exception caught: %s", outputException(exception, false));
+ Logger::warn("Could not spawn vehicle, exception caught: {}", outputException(exception, false));
return strf("Could not spawn vehicle");
}
}
@@ -469,8 +469,8 @@ String CommandProcessor::spawnStagehand(ConnectionId connectionId, String const&
return done ? "" : "Invalid client state";
} catch (StarException const& exception) {
- Logger::warn("Could not spawn Stagehand of type '%s', exception caught: %s", argumentString, outputException(exception, false));
- return strf("Could not spawn Stagehand of type '%s'", argumentString);
+ Logger::warn("Could not spawn Stagehand of type '{}', exception caught: {}", argumentString, outputException(exception, false));
+ return strf("Could not spawn Stagehand of type '{}'", argumentString);
}
}
@@ -487,7 +487,7 @@ String CommandProcessor::clearStagehand(ConnectionId connectionId, String const&
++removed;
}
});
- return done ? strf("Removed %s stagehands", removed) : "Invalid client state";
+ return done ? strf("Removed {} stagehands", removed) : "Invalid client state";
}
String CommandProcessor::spawnLiquid(ConnectionId connectionId, String const& argumentString) {
@@ -500,7 +500,7 @@ String CommandProcessor::spawnLiquid(ConnectionId connectionId, String const& ar
auto liquidsDatabase = Root::singleton().liquidsDatabase();
if (!liquidsDatabase->isLiquidName(arguments.at(0)))
- return strf("No such liquid %d", arguments.at(0));
+ return strf("No such liquid {}", arguments.at(0));
LiquidId liquid = liquidsDatabase->liquidId(arguments.at(0));
@@ -509,7 +509,7 @@ String CommandProcessor::spawnLiquid(ConnectionId connectionId, String const& ar
if (auto maybeQuantity = maybeLexicalCast<float>(arguments.at(1)))
quantity = *maybeQuantity;
else
- return strf("Could not parse quantity value '%s'", arguments.at(1));
+ return strf("Could not parse quantity value '{}'", arguments.at(1));
}
bool done = m_universe->executeForClient(connectionId, [&](WorldServer* world, PlayerPtr const& player) {
@@ -519,7 +519,7 @@ String CommandProcessor::spawnLiquid(ConnectionId connectionId, String const& ar
} catch (StarException const& exception) {
Logger::warn(
- "Could not spawn liquid '%s', exception caught: %s", argumentString, outputException(exception, false));
+ "Could not spawn liquid '{}', exception caught: {}", argumentString, outputException(exception, false));
return "Could not spawn liquid.";
}
}
@@ -535,7 +535,7 @@ String CommandProcessor::kick(ConnectionId connectionId, String const& argumentS
auto toKick = playerCidFromCommand(arguments[0], m_universe);
if (!toKick)
- return strf("No user with specifier %s found.", arguments[0]);
+ return strf("No user with specifier {} found.", arguments[0]);
// Like IRC, if only the nick is passed then the nick is used as the reason
if (arguments.size() == 1)
@@ -543,7 +543,7 @@ String CommandProcessor::kick(ConnectionId connectionId, String const& argumentS
m_universe->disconnectClient(*toKick, arguments[1]);
- return strf("Successfully kicked user with specifier %s. ConnectionId: %s. Reason given: %s",
+ return strf("Successfully kicked user with specifier {}. ConnectionId: {}. Reason given: {}",
arguments[0],
toKick,
arguments[1]);
@@ -560,7 +560,7 @@ String CommandProcessor::ban(ConnectionId connectionId, String const& argumentSt
auto toKick = playerCidFromCommand(arguments[0], m_universe);
if (!toKick)
- return strf("No user with specifier %s found.", arguments[0]);
+ return strf("No user with specifier {} found.", arguments[0]);
String reason = arguments[0];
if (arguments.size() < 2)
@@ -578,7 +578,7 @@ String CommandProcessor::ban(ConnectionId connectionId, String const& argumentSt
} else if (arguments[2] == "both") {
type = {true, true};
} else {
- return strf("Invalid argument %s passed as ban type to /ban. Options are ip, uuid, or both.", arguments[2]);
+ return strf("Invalid argument {} passed as ban type to /ban. Options are ip, uuid, or both.", arguments[2]);
}
}
@@ -587,13 +587,13 @@ String CommandProcessor::ban(ConnectionId connectionId, String const& argumentSt
try {
banTime = lexicalCast<int>(arguments[3]);
} catch (BadLexicalCast const&) {
- return strf("Invalid argument %s passed as ban time to /ban.", arguments[3]);
+ return strf("Invalid argument {} passed as ban time to /ban.", arguments[3]);
}
}
m_universe->banUser(*toKick, reason, type, banTime);
- return strf("Successfully kicked user with specifier %s. ConnectionId: %s. Reason given: %s",
+ return strf("Successfully kicked user with specifier {}. ConnectionId: {}. Reason given: {}",
arguments[0], toKick, reason);
}
@@ -609,9 +609,9 @@ String CommandProcessor::unbanIp(ConnectionId connectionId, String const& argume
bool success = m_universe->unbanIp(arguments[0]);
if (success)
- return strf("Successfully removed IP %s from ban list", arguments[0]);
+ return strf("Successfully removed IP {} from ban list", arguments[0]);
else
- return strf("'%s' is not a valid IP or was not found in the bans list", arguments[0]);
+ return strf("'{}' is not a valid IP or was not found in the bans list", arguments[0]);
}
String CommandProcessor::unbanUuid(ConnectionId connectionId, String const& argumentString) {
@@ -626,9 +626,9 @@ String CommandProcessor::unbanUuid(ConnectionId connectionId, String const& argu
bool success = m_universe->unbanUuid(arguments[0]);
if (success)
- return strf("Successfully removed UUID %s from ban list", arguments[0]);
+ return strf("Successfully removed UUID {} from ban list", arguments[0]);
else
- return strf("'%s' is not a valid UUID or was not found in the bans list", arguments[0]);
+ return strf("'{}' is not a valid UUID or was not found in the bans list", arguments[0]);
}
String CommandProcessor::list(ConnectionId connectionId, String const&) {
@@ -639,7 +639,7 @@ String CommandProcessor::list(ConnectionId connectionId, String const&) {
auto assets = Root::singleton().assets();
for (auto cid : m_universe->clientIds())
- res.append(strf("$%s : %s : $$%s", cid, m_universe->clientNick(cid), m_universe->uuidForClient(cid)->hex()));
+ res.append(strf("${} : {} : $${}", cid, m_universe->clientNick(cid), m_universe->uuidForClient(cid)->hex()));
return res.join("\n");
}
@@ -652,15 +652,15 @@ String CommandProcessor::clientCoordinate(ConnectionId connectionId, String cons
if (arguments.size() > 0) {
auto cid = playerCidFromCommand(arguments[0], m_universe);
if (!cid)
- return strf("No user with specifier %s found.", arguments[0]);
+ return strf("No user with specifier {} found.", arguments[0]);
targetClientId = *cid;
- targetLabel = strf("Client %s's", arguments[0]);
+ targetLabel = strf("Client {}'s", arguments[0]);
}
}
if (targetClientId) {
auto worldId = m_universe->clientWorld(targetClientId);
- return strf("%s current location is %s", targetLabel, worldId);
+ return strf("{} current location is {}", targetLabel, worldId);
} else {
return "";
}
@@ -796,7 +796,7 @@ String CommandProcessor::addBiomeRegion(ConnectionId connectionId, String const&
world->addBiomeRegion(Vec2I::floor(player->aimPosition()), biomeName, subBlockSelector, width);
});
- return done ? strf("added region of biome %s with width %s", biomeName, width) : "failed to add biome region";
+ return done ? strf("added region of biome {} with width {}", biomeName, width) : "failed to add biome region";
}
String CommandProcessor::expandBiomeRegion(ConnectionId connectionId, String const& argumentString) {
@@ -812,7 +812,7 @@ String CommandProcessor::expandBiomeRegion(ConnectionId connectionId, String con
world->expandBiomeRegion(Vec2I::floor(player->aimPosition()), newWidth);
});
- return done ? strf("expanded region to width %s", newWidth) : "failed to expand biome region";
+ return done ? strf("expanded region to width {}", newWidth) : "failed to expand biome region";
}
String CommandProcessor::updatePlanetType(ConnectionId connectionId, String const& argumentString) {
@@ -827,7 +827,7 @@ String CommandProcessor::updatePlanetType(ConnectionId connectionId, String cons
bool done = m_universe->updatePlanetType(coordinate, newType, weatherBiome);
- return done ? strf("set planet at %s to type %s weatherBiome %s", coordinate, newType, weatherBiome) : "failed to update planet type";
+ return done ? strf("set planet at {} to type {} weatherBiome {}", coordinate, newType, weatherBiome) : "failed to update planet type";
}
String CommandProcessor::setEnvironmentBiome(ConnectionId connectionId, String const&) {
@@ -982,7 +982,7 @@ String CommandProcessor::handleCommand(ConnectionId connectionId, String const&
return toString(*res);
} else {
- return strf("No such command %s", command);
+ return strf("No such command {}", command);
}
}
@@ -995,7 +995,7 @@ Maybe<String> CommandProcessor::adminCheck(ConnectionId connectionId, String con
return {"Admin commands disabled on this server."};
if (!config->get("allowAdminCommandsFromAnyone").toBool()) {
if (!m_universe->isAdmin(connectionId))
- return {strf("Insufficient privileges to %s.", commandDescription)};
+ return {strf("Insufficient privileges to {}.", commandDescription)};
}
return {};
@@ -1006,7 +1006,7 @@ Maybe<String> CommandProcessor::localCheck(ConnectionId connectionId, String con
return {};
if (!m_universe->isLocal(connectionId))
- return {strf("The %s command can only be used locally.", commandDescription)};
+ return {strf("The {} command can only be used locally.", commandDescription)};
return {};
}
diff --git a/source/game/StarDamageDatabase.cpp b/source/game/StarDamageDatabase.cpp
index 872b34f..9982a35 100644
--- a/source/game/StarDamageDatabase.cpp
+++ b/source/game/StarDamageDatabase.cpp
@@ -24,7 +24,7 @@ DamageDatabase::DamageDatabase() {
auto config = assets->json(file);
String name = config.getString("kind");
if (m_damageKinds.contains(name))
- throw StarException(strf("Duplicate damage kind Name %s. configfile %s", name, file));
+ throw StarException(strf("Duplicate damage kind Name {}. configfile {}", name, file));
DamageKind kind;
kind.name = name;
@@ -41,7 +41,7 @@ DamageDatabase::DamageDatabase() {
}
kind.elementalType = config.getString("elementalType", "default");
if (!m_elementalTypes.contains(kind.elementalType))
- throw StarException(strf("Undefined elemental type %s in damage kind %s", kind.elementalType, name));
+ throw StarException(strf("Undefined elemental type {} in damage kind {}", kind.elementalType, name));
m_damageKinds.set(name, move(kind));
}
@@ -54,14 +54,14 @@ DamageKind const& DamageDatabase::damageKind(String kind) const {
kind = kind.toLower();
if (!m_damageKinds.contains(kind))
- throw StarException(strf("Unknown damage definition with kind '%s'.", kind));
+ throw StarException(strf("Unknown damage definition with kind '{}'.", kind));
return m_damageKinds.get(kind);
}
ElementalType const& DamageDatabase::elementalType(String const& name) const {
if (!m_damageKinds.contains(name))
- throw StarException(strf("Unknown elemental type with name '%s'.", name));
+ throw StarException(strf("Unknown elemental type with name '{}'.", name));
return m_elementalTypes.get(name);
}
diff --git a/source/game/StarDanceDatabase.cpp b/source/game/StarDanceDatabase.cpp
index 594fde4..3ad2277 100644
--- a/source/game/StarDanceDatabase.cpp
+++ b/source/game/StarDanceDatabase.cpp
@@ -11,7 +11,7 @@ DanceDatabase::DanceDatabase() {
DancePtr dance = readDance(file);
m_dances[dance->name] = dance;
} catch (std::exception const& e) {
- Logger::error("Error loading dance file %s: %s", file, outputException(e, true));
+ Logger::error("Error loading dance file {}: {}", file, outputException(e, true));
}
}
}
diff --git a/source/game/StarDungeonGenerator.cpp b/source/game/StarDungeonGenerator.cpp
index b12c1e1..4014b34 100644
--- a/source/game/StarDungeonGenerator.cpp
+++ b/source/game/StarDungeonGenerator.cpp
@@ -114,7 +114,7 @@ namespace Dungeon {
if (key == "doNotCombineWith")
return as<Rule>(make_shared<const DoNotCombineWithRule>(rule));
- Logger::error("Unknown dungeon rule: %s", key);
+ Logger::error("Unknown dungeon rule: {}", key);
return Maybe<RuleConstPtr>();
}
@@ -272,7 +272,7 @@ namespace Dungeon {
return parseWireBrush(brush);
if (key == "playerstart")
return as<Brush>(make_shared<PlayerStartBrush>());
- throw DungeonException::format("Unknown dungeon brush: %s", key);
+ throw DungeonException::format("Unknown dungeon brush: {}", key);
}
RandomBrush::RandomBrush(Json const& brush) {
@@ -505,7 +505,7 @@ namespace Dungeon {
void InvalidBrush::paint(Vec2I, Phase, DungeonGeneratorWriter*) const {
if (m_nameHint)
- Logger::error("Invalid tile '%s'", *m_nameHint);
+ Logger::error("Invalid tile '{}'", *m_nameHint);
else
Logger::error("Invalid tile");
}
@@ -573,7 +573,7 @@ namespace Dungeon {
return make_shared<const Part>(dungeon, definition, make_shared<ImagePartReader>(*tileset));
} else if (kind == "tmx")
return make_shared<const Part>(dungeon, definition, make_shared<TMXPartReader>());
- throw DungeonException::format("Unknown dungeon part kind: %s", kind);
+ throw DungeonException::format("Unknown dungeon part kind: {}", kind);
}
Part::Part(DungeonDefinition* dungeon, Json const& part, PartReaderPtr reader) {
@@ -706,7 +706,7 @@ namespace Dungeon {
m_reader->forEachTile([&result, pos, &places](Vec2I tilePos, Tile const& tile) -> bool {
if (tile.collidesWithPlaces())
if (places.contains(pos + tilePos)) {
- Logger::debug("Tile collided with place at %s", pos + tilePos);
+ Logger::debug("Tile collided with place at {}", pos + tilePos);
result = true;
return true;
}
@@ -759,7 +759,7 @@ namespace Dungeon {
try {
tile.place(position, phase, writer);
} catch (std::exception const&) {
- Logger::error("Error at map position %s:", tilePos);
+ Logger::error("Error at map position {}:", tilePos);
throw;
}
}
@@ -839,14 +839,14 @@ namespace Dungeon {
d = pickByNeighbours(position);
if (d == Direction::Unknown)
d = pickByEdge(position, m_size);
- Logger::debug("Found connector on %s at %s group %s direction %s", m_name, position, tile.connector->value, (int)d);
+ Logger::debug("Found connector on {} at {} group {} direction {}", m_name, position, tile.connector->value, (int)d);
m_connections.append(make_shared<Connector>(this, tile.connector->value, tile.connector->forwardOnly, d, position));
}
return false;
});
} catch (std::exception& e) {
- throw DungeonException(strf("Exception %s in connector %s", outputException(e, true), m_name));
+ throw DungeonException(strf("Exception {} in connector {}", outputException(e, true), m_name));
}
}
@@ -879,7 +879,7 @@ namespace Dungeon {
return false;
});
} catch (std::exception& e) {
- throw DungeonException(strf("Exception %s in part %s", outputException(e, true), m_name));
+ throw DungeonException(strf("Exception {} in part {}", outputException(e, true), m_name));
}
highestGound = max(highestGound, highestLiquid);
@@ -1321,7 +1321,7 @@ DungeonDefinitionConstPtr DungeonDefinitions::get(String const& name) const {
[this](String const& name) -> DungeonDefinitionPtr {
if (auto path = m_paths.maybe(name))
return readDefinition(*path);
- throw DungeonException::format("Unknown dungeon: '%s'", name);
+ throw DungeonException::format("Unknown dungeon: '{}'", name);
});
}
@@ -1335,7 +1335,7 @@ DungeonDefinitionPtr DungeonDefinitions::readDefinition(String const& path) {
auto assets = Root::singleton().assets();
return make_shared<DungeonDefinition>(assets->json(path).toObject(), AssetPath::directory(path));
} catch (std::exception const& e) {
- throw DungeonException::format("Error loading dungeon '%s': %s", path, outputException(e, false));
+ throw DungeonException::format("Error loading dungeon '{}': {}", path, outputException(e, false));
}
}
@@ -1362,7 +1362,7 @@ DungeonDefinition::DungeonDefinition(JsonObject const& definition, String const&
for (auto const& partsDefMap : definition.get("parts").iterateArray()) {
Dungeon::PartConstPtr part = parsePart(this, partsDefMap, tileset);
if (m_parts.contains(part->name()))
- throw DungeonException::format("Duplicate dungeon part name: %s", part->name());
+ throw DungeonException::format("Duplicate dungeon part name: {}", part->name());
m_parts.insert(part->name(), part);
}
@@ -1434,24 +1434,24 @@ Maybe<pair<List<RectI>, Set<Vec2I>>> DungeonGenerator::generate(DungeonGenerator
try {
Dungeon::DungeonGeneratorWriter writer(facade, markSurfaceAndTerrain ? position[1] : Maybe<int>(), m_def->extendSurfaceFreeSpace());
- Logger::debug(forcePlacement ? "Forcing generation of dungeon %s" : "Generating dungeon %s", m_def->name());
+ Logger::debug(forcePlacement ? "Forcing generation of dungeon {}" : "Generating dungeon {}", m_def->name());
Dungeon::PartConstPtr anchor = pickAnchor();
if (!anchor) {
- Logger::error("No valid anchor piece found for dungeon at %s", position);
+ Logger::error("No valid anchor piece found for dungeon at {}", position);
return {};
}
auto pos = position + Vec2I(0, -anchor->placementLevelConstraint());
if (forcePlacement || anchor->canPlace(pos, &writer)) {
- Logger::info("Placing dungeon at %s", position);
+ Logger::info("Placing dungeon at {}", position);
return buildDungeon(anchor, pos, &writer, forcePlacement);
} else {
- Logger::debug("Failed to place a dungeon at %s", position);
+ Logger::debug("Failed to place a dungeon at {}", position);
return {};
}
} catch (std::exception const& e) {
- throw DungeonException(strf("Error generating dungeon named '%s'", m_def->name()), e);
+ throw DungeonException(strf("Error generating dungeon named '{}'", m_def->name()), e);
}
}
@@ -1464,7 +1464,7 @@ pair<List<RectI>, Set<Vec2I>> DungeonGenerator::buildDungeon(Dungeon::PartConstP
Set<Vec2I> preserveTiles;
int piecesPlaced = 0;
- Logger::debug("Placing dungeon entrance at %s", basePos);
+ Logger::debug("Placing dungeon entrance at {}", basePos);
auto placePart = [&](Dungeon::Part const* part, Vec2I const& placePos) {
Set<Vec2I> clearTileEntityPositions;
@@ -1497,7 +1497,7 @@ pair<List<RectI>, Set<Vec2I>> DungeonGenerator::buildDungeon(Dungeon::PartConstP
placementCounter[part->name()]++;
piecesPlaced++;
- Logger::debug("placed %s", part->name());
+ Logger::debug("placed {}", part->name());
};
placePart(anchor.get(), basePos);
@@ -1509,7 +1509,7 @@ pair<List<RectI>, Set<Vec2I>> DungeonGenerator::buildDungeon(Dungeon::PartConstP
Dungeon::Part const* parentPart = openSet.first().first;
Vec2I parentPos = openSet.first().second;
openSet.takeFirst();
- Logger::debug("Trying to add part %s at %s connectors: %s", parentPart->name(), parentPos, parentPart->connections().size());
+ Logger::debug("Trying to add part {} at {} connectors: {}", parentPart->name(), parentPos, parentPart->connections().size());
for (size_t i = 0; i < parentPart->connections().size(); i++) {
auto connector = parentPart->connections()[i];
Vec2I connectorPos = parentPos + connector->offset();
@@ -1518,7 +1518,7 @@ pair<List<RectI>, Set<Vec2I>> DungeonGenerator::buildDungeon(Dungeon::PartConstP
List<Dungeon::ConnectorConstPtr> options = findConnectablePart(connector);
while (options.size()) {
Dungeon::ConnectorConstPtr option = chooseOption(options, m_rand);
- Logger::debug("Trying part %s", option->part()->name());
+ Logger::debug("Trying part {}", option->part()->name());
Vec2I partPos = connectorPos - option->offset() + option->positionAdjustment();
Vec2I optionPos = connectorPos + option->positionAdjustment();
if (!option->part()->ignoresPartMaximum()) {
@@ -1526,7 +1526,7 @@ pair<List<RectI>, Set<Vec2I>> DungeonGenerator::buildDungeon(Dungeon::PartConstP
continue;
if ((partPos - origin).magnitude() > m_def->maxRadius()) {
- Logger::debug("out of range. %s ... %s", partPos, origin);
+ Logger::debug("out of range. {} ... {}", partPos, origin);
continue;
}
}
diff --git a/source/game/StarDungeonImagePart.cpp b/source/game/StarDungeonImagePart.cpp
index a3fd417..86b3887 100644
--- a/source/game/StarDungeonImagePart.cpp
+++ b/source/game/StarDungeonImagePart.cpp
@@ -35,7 +35,7 @@ namespace Dungeon {
if (exitEarly)
return;
} else {
- throw StarException::format("Dungeon image %s uses unknown tile color: #%02x%02x%02x%02x",
+ throw StarException::format("Dungeon image {} uses unknown tile color: #{:02x}{:02x}{:02x}{:02x}",
file,
tileColor[0],
tileColor[1],
@@ -58,7 +58,7 @@ namespace Dungeon {
if (exitEarly)
return;
} else {
- throw StarException::format("Dungeon image %s uses unknown tile color: #%02x%02x%02x%02x",
+ throw StarException::format("Dungeon image {} uses unknown tile color: #{:02x}{:02x}{:02x}{:02x}",
file,
tileColor[0],
tileColor[1],
@@ -69,7 +69,7 @@ namespace Dungeon {
}
String connectorColorValue(Vec4B const& color) {
- return strf("%d,%d,%d,%d", color[0], color[1], color[2], color[3]);
+ return strf("{},{},{},{}", color[0], color[1], color[2], color[3]);
}
Tile variantMapToTile(JsonObject const& tile) {
diff --git a/source/game/StarDungeonTMXPart.cpp b/source/game/StarDungeonTMXPart.cpp
index 9058a38..c319ab7 100644
--- a/source/game/StarDungeonTMXPart.cpp
+++ b/source/game/StarDungeonTMXPart.cpp
@@ -180,7 +180,7 @@ namespace Dungeon {
m_tileData.append(index.toUInt() & ~TileFlip::AllBits);
}
} else {
- throw StarException::format("TMXTileLayer does not support compression mode %s", layer.getString("compression"));
+ throw StarException::format("TMXTileLayer does not support compression mode {}", layer.getString("compression"));
}
if (m_tileData.count() != width * height)
@@ -208,7 +208,7 @@ namespace Dungeon {
m_objectGroups.append(group);
} else {
- throw StarException(strf("Unknown layer type '%s'", layerType.utf8Ptr()));
+ throw StarException(strf("Unknown layer type '{}'", layerType.utf8Ptr()));
}
}
}
@@ -244,7 +244,7 @@ namespace Dungeon {
TMXTilesets::TMXTilesets(Json const& tmx) {
for (Json const& tilesetJson : tmx.iterateArray()) {
if (!tilesetJson.contains("source"))
- throw StarException::format("Tiled map has embedded tileset %s", tilesetJson.optString("name"));
+ throw StarException::format("Tiled map has embedded tileset {}", tilesetJson.optString("name"));
String sourcePath = tilesetAssetPath(tilesetJson.getString("source"));
Tiled::TilesetConstPtr tileset = Root::singleton().tilesetDatabase()->get(sourcePath);
@@ -407,7 +407,7 @@ namespace Dungeon {
StarException TMXObject::tmxObjectError(Json const& tmx, String const& msg) {
Vec2I pos = getPos(tmx);
- return StarException::format("At %d,%d: %s", pos[0], pos[1], msg);
+ return StarException::format("At {},{}: {}", pos[0], pos[1], msg);
}
TMXObjectGroup::TMXObjectGroup(Json const& tmx, TMXTilesetsPtr tilesets) {
diff --git a/source/game/StarEffectSourceDatabase.cpp b/source/game/StarEffectSourceDatabase.cpp
index d709dfb..5ef83de 100644
--- a/source/game/StarEffectSourceDatabase.cpp
+++ b/source/game/StarEffectSourceDatabase.cpp
@@ -18,7 +18,7 @@ EffectSourceDatabase::EffectSourceDatabase() {
auto sourceConfig = make_shared<EffectSourceConfig>(assets->json(file));
if (m_sourceConfigs.contains(sourceConfig->kind()))
throw StarException(
- strf("Duplicate effect source asset kind Name %s. configfile %s", sourceConfig->kind(), file));
+ strf("Duplicate effect source asset kind Name {}. configfile {}", sourceConfig->kind(), file));
auto k = sourceConfig->kind().toLower();
m_sourceConfigs[k] = sourceConfig;
}
@@ -27,7 +27,7 @@ EffectSourceDatabase::EffectSourceDatabase() {
EffectSourceConfigPtr EffectSourceDatabase::effectSourceConfig(String const& kind) const {
auto k = kind.toLower();
if (!m_sourceConfigs.contains(k))
- throw StarException(strf("Unknown effect source definition with kind '%s'.", kind));
+ throw StarException(strf("Unknown effect source definition with kind '{}'.", kind));
return m_sourceConfigs.get(k);
}
diff --git a/source/game/StarEntityFactory.cpp b/source/game/StarEntityFactory.cpp
index cfab917..333dec1 100644
--- a/source/game/StarEntityFactory.cpp
+++ b/source/game/StarEntityFactory.cpp
@@ -64,7 +64,7 @@ ByteArray EntityFactory::netStoreEntity(EntityPtr const& entity) const {
} else if (auto vehicle = as<Vehicle>(entity)) {
return m_vehicleDatabase->netStore(vehicle);
} else {
- throw EntityFactoryException::format("Don't know how to make net store for entity type '%s'", EntityTypeNames.getRight(entity->entityType()));
+ throw EntityFactoryException::format("Don't know how to make net store for entity type '{}'", EntityTypeNames.getRight(entity->entityType()));
}
}
@@ -92,7 +92,7 @@ EntityPtr EntityFactory::netLoadEntity(EntityType type, ByteArray const& netStor
} else if (type == EntityType::Vehicle) {
return m_vehicleDatabase->netLoad(netStore);
} else {
- throw EntityFactoryException::format("Don't know how to create entity type '%s' from net store", EntityTypeNames.getRight(type));
+ throw EntityFactoryException::format("Don't know how to create entity type '{}' from net store", EntityTypeNames.getRight(type));
}
}
@@ -116,7 +116,7 @@ Json EntityFactory::diskStoreEntity(EntityPtr const& entity) const {
} else if (auto vehicle = as<Vehicle>(entity)) {
return m_vehicleDatabase->diskStore(vehicle);
} else {
- throw EntityFactoryException::format("Don't know how to make disk store for entity type '%s'", EntityTypeNames.getRight(entity->entityType()));
+ throw EntityFactoryException::format("Don't know how to make disk store for entity type '{}'", EntityTypeNames.getRight(entity->entityType()));
}
}
@@ -140,7 +140,7 @@ EntityPtr EntityFactory::diskLoadEntity(EntityType type, Json const& diskStore)
} else if (type == EntityType::Vehicle) {
return m_vehicleDatabase->diskLoad(diskStore);
} else {
- throw EntityFactoryException::format("Don't know how to create entity type '%s' from disk store", EntityTypeNames.getRight(type));
+ throw EntityFactoryException::format("Don't know how to create entity type '{}' from disk store", EntityTypeNames.getRight(type));
}
}
diff --git a/source/game/StarEntityMap.cpp b/source/game/StarEntityMap.cpp
index c04f0d5..a3844dc 100644
--- a/source/game/StarEntityMap.cpp
+++ b/source/game/StarEntityMap.cpp
@@ -34,10 +34,10 @@ void EntityMap::addEntity(EntityPtr entity) {
auto uniqueId = entity->uniqueId();
if (m_spatialMap.contains(entityId))
- throw EntityMapException::format("Duplicate entity id '%s' in EntityMap::addEntity", entityId);
+ throw EntityMapException::format("Duplicate entity id '{}' in EntityMap::addEntity", entityId);
if (boundBox.isNegative() || boundBox.width() > MaximumEntityBoundBox || boundBox.height() > MaximumEntityBoundBox) {
- throw EntityMapException::format("Entity id: %s type: %s bound box is negative or beyond the maximum entity bound box size in EntityMap::addEntity",
+ throw EntityMapException::format("Entity id: {} type: {} bound box is negative or beyond the maximum entity bound box size in EntityMap::addEntity",
entity->entityId(), (int)entity->entityType());
}
@@ -45,7 +45,7 @@ void EntityMap::addEntity(EntityPtr entity) {
throw EntityMapException::format("Null entity id in EntityMap::addEntity");
if (uniqueId && m_uniqueMap.hasLeftValue(*uniqueId))
- throw EntityMapException::format("Duplicate entity unique id (%s) on entity id (%s) in EntityMap::addEntity", *uniqueId, entityId);
+ throw EntityMapException::format("Duplicate entity unique id ({}) on entity id ({}) in EntityMap::addEntity", *uniqueId, entityId);
m_spatialMap.set(entityId, m_geometry.splitRect(boundBox, position), move(entity));
if (uniqueId)
@@ -76,7 +76,7 @@ void EntityMap::updateAllEntities(EntityCallback const& callback, function<bool(
auto boundBox = entity->metaBoundBox();
if (boundBox.isNegative() || boundBox.width() > MaximumEntityBoundBox || boundBox.height() > MaximumEntityBoundBox) {
- throw EntityMapException::format("Entity id: %s type: %s bound box is negative or beyond the maximum entity bound box size in EntityMap::addEntity",
+ throw EntityMapException::format("Entity id: {} type: {} bound box is negative or beyond the maximum entity bound box size in EntityMap::addEntity",
entity->entityId(), (int)entity->entityType());
}
@@ -92,7 +92,7 @@ void EntityMap::updateAllEntities(EntityCallback const& callback, function<bool(
if (uniqueId) {
if (auto existingEntityId = m_uniqueMap.maybeRight(*uniqueId)) {
if (entityId != *existingEntityId)
- throw EntityMapException::format("Duplicate entity unique id on entity ids (%s) and (%s)", *existingEntityId, entityId);
+ throw EntityMapException::format("Duplicate entity unique id on entity ids ({}) and ({})", *existingEntityId, entityId);
} else {
m_uniqueMap.removeRight(entityId);
m_uniqueMap.add(*uniqueId, entityId);
diff --git a/source/game/StarForceRegions.cpp b/source/game/StarForceRegions.cpp
index a0731f0..ec6bddd 100644
--- a/source/game/StarForceRegions.cpp
+++ b/source/game/StarForceRegions.cpp
@@ -193,7 +193,7 @@ PhysicsForceRegion jsonToPhysicsForceRegion(Json const& json) {
else if (type.equalsIgnoreCase("GradientForceRegion"))
return GradientForceRegion::fromJson(json);
else
- throw JsonException::format("No such physics force region type '%s'", type);
+ throw JsonException::format("No such physics force region type '{}'", type);
}
}
diff --git a/source/game/StarGameTypes.cpp b/source/game/StarGameTypes.cpp
index baa2c18..7e47eeb 100644
--- a/source/game/StarGameTypes.cpp
+++ b/source/game/StarGameTypes.cpp
@@ -61,7 +61,7 @@ std::pair<EntityId, EntityId> connectionEntitySpace(ConnectionId connectionId) {
EntityId endIdSpace = beginIdSpace + 65535;
return {beginIdSpace, endIdSpace};
} else {
- throw StarException::format("Invalid connection id in clientEntitySpace(%s)", connectionId);
+ throw StarException::format("Invalid connection id in clientEntitySpace({})", connectionId);
}
}
diff --git a/source/game/StarHumanoid.cpp b/source/game/StarHumanoid.cpp
index 1c23308..68ccecb 100644
--- a/source/game/StarHumanoid.cpp
+++ b/source/game/StarHumanoid.cpp
@@ -497,7 +497,7 @@ List<Drawable> Humanoid::render() {
};
auto backArmDrawable = [&](String const& frameSet, Directives const& directives) -> Drawable {
- String image = strf("%s:%s", frameSet, backHand.backFrame);
+ String image = strf("{}:{}", frameSet, backHand.backFrame);
Drawable backArm = Drawable::makeImage(move(image), 1.0f / TilePixels, true, backArmFrameOffset);
backArm.imagePart().addDirectives(directives);
backArm.rotate(backHand.angle, backArmFrameOffset + m_backArmRotationCenter + m_backArmOffset);
@@ -510,11 +510,11 @@ List<Drawable> Humanoid::render() {
frameGroup = "runbackwards";
String image;
if (dance.isValid() && danceStep->bodyFrame)
- image = strf("%s:%s", m_backArmorFrameset, *danceStep->bodyFrame);
+ image = strf("{}:{}", m_backArmorFrameset, *danceStep->bodyFrame);
else if (m_state == Idle)
- image = strf("%s:%s", m_backArmorFrameset, m_identity.personality.idle);
+ image = strf("{}:{}", m_backArmorFrameset, m_identity.personality.idle);
else
- image = strf("%s:%s.%s", m_backArmorFrameset, frameGroup, bodyStateSeq);
+ image = strf("{}:{}.{}", m_backArmorFrameset, frameGroup, bodyStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, Vec2F());
drawable.imagePart().addDirectives(getBackDirectives(), true);
@@ -542,13 +542,13 @@ List<Drawable> Humanoid::render() {
String image;
Vec2F position;
if (dance.isValid() && danceStep->backArmFrame) {
- image = strf("%s:%s", m_backArmFrameset, *danceStep->backArmFrame);
+ image = strf("{}:{}", m_backArmFrameset, *danceStep->backArmFrame);
position = danceStep->backArmOffset / TilePixels;
} else if (m_state == Idle) {
- image = strf("%s:%s", m_backArmFrameset, m_identity.personality.armIdle);
+ image = strf("{}:{}", m_backArmFrameset, m_identity.personality.armIdle);
position = m_identity.personality.armOffset / TilePixels;
} else
- image = strf("%s:%s.%s", m_backArmFrameset, frameBase(m_state), armStateSeq);
+ image = strf("{}:{}.{}", m_backArmFrameset, frameBase(m_state), armStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, position);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
if (dance.isValid())
@@ -559,13 +559,13 @@ List<Drawable> Humanoid::render() {
String image;
Vec2F position;
if (dance.isValid() && danceStep->backArmFrame) {
- image = strf("%s:%s", m_backSleeveFrameset, *danceStep->backArmFrame);
+ image = strf("{}:{}", m_backSleeveFrameset, *danceStep->backArmFrame);
position = danceStep->backArmOffset / TilePixels;
} else if (m_state == Idle) {
- image = strf("%s:%s", m_backSleeveFrameset, m_identity.personality.armIdle);
+ image = strf("{}:{}", m_backSleeveFrameset, m_identity.personality.armIdle);
position = m_identity.personality.armOffset / TilePixels;
} else
- image = strf("%s:%s.%s", m_backSleeveFrameset, frameBase(m_state), armStateSeq);
+ image = strf("{}:{}.{}", m_backSleeveFrameset, frameBase(m_state), armStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, position);
drawable.imagePart().addDirectives(getChestDirectives(), true);
if (dance.isValid())
@@ -591,21 +591,21 @@ List<Drawable> Humanoid::render() {
headPosition += m_headLayOffset;
if (!m_headFrameset.empty() && !m_bodyHidden) {
- String image = strf("%s:normal", m_headFrameset);
+ String image = strf("{}:normal", m_headFrameset);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable), m_bodyFullbright);
}
if (!m_emoteFrameset.empty() && !m_bodyHidden) {
- String image = strf("%s:%s.%s", m_emoteFrameset, emoteFrameBase(m_emoteState), emoteStateSeq);
+ String image = strf("{}:{}.{}", m_emoteFrameset, emoteFrameBase(m_emoteState), emoteStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getEmoteDirectives(), true);
addDrawable(move(drawable), m_bodyFullbright);
}
if (!m_hairFrameset.empty() && !m_bodyHidden) {
- String image = strf("%s:normal", m_hairFrameset);
+ String image = strf("{}:normal", m_hairFrameset);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getHairDirectives(), true).addDirectives(getHelmetMaskDirectives(), true);
addDrawable(move(drawable), m_bodyFullbright);
@@ -614,11 +614,11 @@ List<Drawable> Humanoid::render() {
if (!m_bodyFrameset.empty() && !m_bodyHidden) {
String image;
if (dance.isValid() && danceStep->bodyFrame)
- image = strf("%s:%s", m_bodyFrameset, *danceStep->bodyFrame);
+ image = strf("{}:{}", m_bodyFrameset, *danceStep->bodyFrame);
else if (m_state == Idle)
- image = strf("%s:%s", m_bodyFrameset, m_identity.personality.idle);
+ image = strf("{}:{}", m_bodyFrameset, m_identity.personality.idle);
else
- image = strf("%s:%s.%s", m_bodyFrameset, frameBase(m_state), bodyStateSeq);
+ image = strf("{}:{}.{}", m_bodyFrameset, frameBase(m_state), bodyStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, {});
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable), m_bodyFullbright);
@@ -627,11 +627,11 @@ List<Drawable> Humanoid::render() {
if (!m_legsArmorFrameset.empty()) {
String image;
if (dance.isValid() && danceStep->bodyFrame)
- image = strf("%s:%s", m_legsArmorFrameset, *danceStep->bodyFrame);
+ image = strf("{}:{}", m_legsArmorFrameset, *danceStep->bodyFrame);
else if (m_state == Idle)
- image = strf("%s:%s", m_legsArmorFrameset, m_identity.personality.idle);
+ image = strf("{}:{}", m_legsArmorFrameset, m_identity.personality.idle);
else
- image = strf("%s:%s.%s", m_legsArmorFrameset, frameBase(m_state), bodyStateSeq);
+ image = strf("{}:{}.{}", m_legsArmorFrameset, frameBase(m_state), bodyStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, {});
drawable.imagePart().addDirectives(getLegsDirectives(), true);
addDrawable(move(drawable));
@@ -641,17 +641,17 @@ List<Drawable> Humanoid::render() {
String image;
Vec2F position;
if (dance.isValid() && danceStep->bodyFrame)
- image = strf("%s:%s", m_chestArmorFrameset, *danceStep->bodyFrame);
+ image = strf("{}:{}", m_chestArmorFrameset, *danceStep->bodyFrame);
else if (m_state == Run)
- image = strf("%s:run", m_chestArmorFrameset);
+ image = strf("{}:run", m_chestArmorFrameset);
else if (m_state == Idle)
- image = strf("%s:%s", m_chestArmorFrameset, m_identity.personality.idle);
+ image = strf("{}:{}", m_chestArmorFrameset, m_identity.personality.idle);
else if (m_state == Duck)
- image = strf("%s:duck", m_chestArmorFrameset);
+ image = strf("{}:duck", m_chestArmorFrameset);
else if ((m_state == Swim) || (m_state == SwimIdle))
- image = strf("%s:swim", m_chestArmorFrameset);
+ image = strf("{}:swim", m_chestArmorFrameset);
else
- image = strf("%s:chest.1", m_chestArmorFrameset);
+ image = strf("{}:chest.1", m_chestArmorFrameset);
if (m_state != Duck)
position[1] += bobYOffset;
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, position);
@@ -660,28 +660,28 @@ List<Drawable> Humanoid::render() {
}
if (!m_facialHairFrameset.empty() && !m_bodyHidden) {
- String image = strf("%s:normal", m_facialHairFrameset);
+ String image = strf("{}:normal", m_facialHairFrameset);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getFacialHairDirectives(), true).addDirectives(getHelmetMaskDirectives(), true);
addDrawable(move(drawable), m_bodyFullbright);
}
if (!m_facialMaskFrameset.empty() && !m_bodyHidden) {
- String image = strf("%s:normal", m_facialMaskFrameset);
+ String image = strf("{}:normal", m_facialMaskFrameset);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getFacialMaskDirectives(), true).addDirectives(getHelmetMaskDirectives(), true);
addDrawable(move(drawable));
}
if (!m_headArmorFrameset.empty()) {
- String image = strf("%s:normal", m_headArmorFrameset);
+ String image = strf("{}:normal", m_headArmorFrameset);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, headPosition);
drawable.imagePart().addDirectives(getHeadDirectives(), true);
addDrawable(move(drawable));
}
auto frontArmDrawable = [&](String const& frameSet, Directives const& directives) -> Drawable {
- String image = strf("%s:%s", frameSet, frontHand.frontFrame);
+ String image = strf("{}:{}", frameSet, frontHand.frontFrame);
Drawable frontArm = Drawable::makeImage(image, 1.0f / TilePixels, true, frontArmFrameOffset);
frontArm.imagePart().addDirectives(directives);
frontArm.rotate(frontHand.angle, frontArmFrameOffset + m_frontArmRotationCenter);
@@ -710,13 +710,13 @@ List<Drawable> Humanoid::render() {
String image;
Vec2F position;
if (dance.isValid() && danceStep->frontArmFrame) {
- image = strf("%s:%s", m_frontArmFrameset, *danceStep->frontArmFrame);
+ image = strf("{}:{}", m_frontArmFrameset, *danceStep->frontArmFrame);
position = danceStep->frontArmOffset / TilePixels;
} else if (m_state == Idle) {
- image = strf("%s:%s", m_frontArmFrameset, m_identity.personality.armIdle);
+ image = strf("{}:{}", m_frontArmFrameset, m_identity.personality.armIdle);
position = m_identity.personality.armOffset / TilePixels;
} else
- image = strf("%s:%s.%s", m_frontArmFrameset, frameBase(m_state), armStateSeq);
+ image = strf("{}:{}.{}", m_frontArmFrameset, frameBase(m_state), armStateSeq);
auto drawable = Drawable::makeImage(move(image), 1.0f / TilePixels, true, position);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
if (dance.isValid())
@@ -728,13 +728,13 @@ List<Drawable> Humanoid::render() {
String image;
Vec2F position;
if (dance.isValid() && danceStep->frontArmFrame) {
- image = strf("%s:%s", m_frontSleeveFrameset, *danceStep->frontArmFrame);
+ image = strf("{}:{}", m_frontSleeveFrameset, *danceStep->frontArmFrame);
position = danceStep->frontArmOffset / TilePixels;
} else if (m_state == Idle) {
- image = strf("%s:%s", m_frontSleeveFrameset, m_identity.personality.armIdle);
+ image = strf("{}:{}", m_frontSleeveFrameset, m_identity.personality.armIdle);
position = m_identity.personality.armOffset / TilePixels;
} else
- image = strf("%s:%s.%s", m_frontSleeveFrameset, frameBase(m_state), armStateSeq);
+ image = strf("{}:{}.{}", m_frontSleeveFrameset, frameBase(m_state), armStateSeq);
auto drawable = Drawable::makeImage(image, 1.0f / TilePixels, true, position);
drawable.imagePart().addDirectives(getChestDirectives(), true);
if (dance.isValid())
@@ -744,7 +744,7 @@ List<Drawable> Humanoid::render() {
}
if (m_drawVaporTrail) {
- auto image = strf("%s:%d",
+ auto image = strf("{}:{}",
m_vaporTrailFrameset,
m_timing.genericSeq(m_animationTimer, m_vaporTrailCycle, m_vaporTrailFrames, true));
addDrawable(Drawable::makeImage(AssetPath::split(image), 1.0f / TilePixels, true, {}));
@@ -786,20 +786,20 @@ List<Drawable> Humanoid::renderPortrait(PortraitMode mode) const {
if (mode != PortraitMode::Head) {
if (!m_backArmFrameset.empty()) {
- String image = strf("%s:%s", m_backArmFrameset, personality.armIdle);
+ String image = strf("{}:{}", m_backArmFrameset, personality.armIdle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.armOffset);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable));
}
if (dressed && !m_backSleeveFrameset.empty()) {
- String image = strf("%s:%s", m_backSleeveFrameset, personality.armIdle);
+ String image = strf("{}:{}", m_backSleeveFrameset, personality.armIdle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.armOffset);
drawable.imagePart().addDirectives(getChestDirectives(), true);
addDrawable(move(drawable));
}
if (mode != PortraitMode::Bust) {
if (dressed && !m_backArmorFrameset.empty()) {
- String image = strf("%s:%s", m_backArmorFrameset, personality.idle);
+ String image = strf("{}:{}", m_backArmorFrameset, personality.idle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, {});
drawable.imagePart().addDirectives(getBackDirectives(), true);
addDrawable(move(drawable));
@@ -808,28 +808,28 @@ List<Drawable> Humanoid::renderPortrait(PortraitMode mode) const {
}
if (!m_headFrameset.empty()) {
- String image = strf("%s:normal", m_headFrameset);
+ String image = strf("{}:normal", m_headFrameset);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable));
}
if (!m_emoteFrameset.empty()) {
- String image = strf("%s:%s.%s", m_emoteFrameset, emoteFrameBase(m_emoteState), emoteStateSeq);
+ String image = strf("{}:{}.{}", m_emoteFrameset, emoteFrameBase(m_emoteState), emoteStateSeq);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getEmoteDirectives(), true);
addDrawable(move(drawable));
}
if (!m_hairFrameset.empty()) {
- String image = strf("%s:normal", m_hairFrameset);
+ String image = strf("{}:normal", m_hairFrameset);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getHairDirectives(), true).addDirectives(helmetMaskDirective, true);
addDrawable(move(drawable));
}
if (!m_bodyFrameset.empty()) {
- String image = strf("%s:%s", m_bodyFrameset, personality.idle);
+ String image = strf("{}:{}", m_bodyFrameset, personality.idle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, {});
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable));
@@ -837,14 +837,14 @@ List<Drawable> Humanoid::renderPortrait(PortraitMode mode) const {
if (mode != PortraitMode::Head) {
if (dressed && !m_legsArmorFrameset.empty()) {
- String image = strf("%s:%s", m_legsArmorFrameset, personality.idle);
+ String image = strf("{}:{}", m_legsArmorFrameset, personality.idle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, {});
drawable.imagePart().addDirectives(getLegsDirectives(), true);
addDrawable(move(drawable));
}
if (dressed && !m_chestArmorFrameset.empty()) {
- String image = strf("%s:%s", m_chestArmorFrameset, personality.idle);
+ String image = strf("{}:{}", m_chestArmorFrameset, personality.idle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, {});
drawable.imagePart().addDirectives(getChestDirectives(), true);
addDrawable(move(drawable));
@@ -852,21 +852,21 @@ List<Drawable> Humanoid::renderPortrait(PortraitMode mode) const {
}
if (!m_facialHairFrameset.empty()) {
- String image = strf("%s:normal", m_facialHairFrameset);
+ String image = strf("{}:normal", m_facialHairFrameset);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getFacialHairDirectives(), true).addDirectives(helmetMaskDirective, true);
addDrawable(move(drawable));
}
if (!m_facialMaskFrameset.empty()) {
- String image = strf("%s:normal", m_facialMaskFrameset);
+ String image = strf("{}:normal", m_facialMaskFrameset);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getFacialMaskDirectives(), true).addDirectives(helmetMaskDirective, true);
addDrawable(move(drawable));
}
if (dressed && !m_headArmorFrameset.empty()) {
- String image = strf("%s:normal", m_headArmorFrameset);
+ String image = strf("{}:normal", m_headArmorFrameset);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.headOffset);
drawable.imagePart().addDirectives(getHeadDirectives(), true);
addDrawable(move(drawable));
@@ -874,14 +874,14 @@ List<Drawable> Humanoid::renderPortrait(PortraitMode mode) const {
if (mode != PortraitMode::Head) {
if (!m_frontArmFrameset.empty()) {
- String image = strf("%s:%s", m_frontArmFrameset, personality.armIdle);
+ String image = strf("{}:{}", m_frontArmFrameset, personality.armIdle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.armOffset);
drawable.imagePart().addDirectives(getBodyDirectives(), true);
addDrawable(move(drawable));
}
if (dressed && !m_frontSleeveFrameset.empty()) {
- String image = strf("%s:%s", m_frontSleeveFrameset, personality.armIdle);
+ String image = strf("{}:{}", m_frontSleeveFrameset, personality.armIdle);
Drawable drawable = Drawable::makeImage(move(image), 1.0f, true, personality.armOffset);
drawable.imagePart().addDirectives(getChestDirectives(), true);
addDrawable(move(drawable));
@@ -1025,7 +1025,7 @@ String Humanoid::frameBase(State state) const {
return "lay";
default:
- throw StarException(strf("No such state '%s'", StateNames.getRight(state)));
+ throw StarException(strf("No such state '{}'", StateNames.getRight(state)));
}
}
@@ -1061,30 +1061,30 @@ String Humanoid::emoteFrameBase(HumanoidEmote state) const {
return "sleep";
default:
- throw StarException(strf("No such emote state '%s'", HumanoidEmoteNames.getRight(state)));
+ throw StarException(strf("No such emote state '{}'", HumanoidEmoteNames.getRight(state)));
}
}
String Humanoid::getHeadFromIdentity() const {
- return strf("/humanoid/%s/%shead.png",
+ return strf("/humanoid/{}/{}head.png",
m_identity.imagePath ? *m_identity.imagePath : m_identity.species,
GenderNames.getRight(m_identity.gender));
}
String Humanoid::getBodyFromIdentity() const {
- return strf("/humanoid/%s/%sbody.png",
+ return strf("/humanoid/{}/{}body.png",
m_identity.imagePath ? *m_identity.imagePath : m_identity.species,
GenderNames.getRight(m_identity.gender));
}
String Humanoid::getFacialEmotesFromIdentity() const {
- return strf("/humanoid/%s/emote.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
+ return strf("/humanoid/{}/emote.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
}
String Humanoid::getHairFromIdentity() const {
if (m_identity.hairType.empty())
return "";
- return strf("/humanoid/%s/%s/%s.png",
+ return strf("/humanoid/{}/{}/{}.png",
m_identity.imagePath ? *m_identity.imagePath : m_identity.species,
m_identity.hairGroup,
m_identity.hairType);
@@ -1093,7 +1093,7 @@ String Humanoid::getHairFromIdentity() const {
String Humanoid::getFacialHairFromIdentity() const {
if (m_identity.facialHairType.empty())
return "";
- return strf("/humanoid/%s/%s/%s.png",
+ return strf("/humanoid/{}/{}/{}.png",
m_identity.imagePath ? *m_identity.imagePath : m_identity.species,
m_identity.facialHairGroup,
m_identity.facialHairType);
@@ -1102,18 +1102,18 @@ String Humanoid::getFacialHairFromIdentity() const {
String Humanoid::getFacialMaskFromIdentity() const {
if (m_identity.facialMaskType.empty())
return "";
- return strf("/humanoid/%s/%s/%s.png",
+ return strf("/humanoid/{}/{}/{}.png",
m_identity.imagePath ? *m_identity.imagePath : m_identity.species,
m_identity.facialMaskGroup,
m_identity.facialMaskType);
}
String Humanoid::getBackArmFromIdentity() const {
- return strf("/humanoid/%s/backarm.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
+ return strf("/humanoid/{}/backarm.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
}
String Humanoid::getFrontArmFromIdentity() const {
- return strf("/humanoid/%s/frontarm.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
+ return strf("/humanoid/{}/frontarm.png", m_identity.imagePath ? *m_identity.imagePath : m_identity.species);
}
String Humanoid::getVaporTrailFrameset() const {
diff --git a/source/game/StarInventoryTypes.cpp b/source/game/StarInventoryTypes.cpp
index 09fa457..46892a8 100644
--- a/source/game/StarInventoryTypes.cpp
+++ b/source/game/StarInventoryTypes.cpp
@@ -54,11 +54,11 @@ std::ostream& operator<<(std::ostream& ostream, InventorySlot const& slot) {
Json location = json.get("location", {});
if (location.isNull())
- format(ostream, "InventorySlot{type: %s}", type);
+ format(ostream, "InventorySlot{type: {}}", type);
if (location.isType(Json::Type::String))
- format(ostream, "InventorySlot{type: %s, location: %s}", type, location.toString());
+ format(ostream, "InventorySlot{type: {}, location: {}}", type, location.toString());
else
- format(ostream, "InventorySlot{type: %s, location: %s}", type, location.toInt());
+ format(ostream, "InventorySlot{type: {}, location: {}}", type, location.toInt());
return ostream;
}
diff --git a/source/game/StarItem.cpp b/source/game/StarItem.cpp
index 4e4ec14..3658bb0 100644
--- a/source/game/StarItem.cpp
+++ b/source/game/StarItem.cpp
@@ -128,7 +128,7 @@ ItemPtr Item::take(uint64_t max) {
newItems->setCount(takeCount);
return newItems;
} else {
- Logger::warn(strf("Could not clone %s, not moving %d items as requested.", friendlyName(), takeCount).c_str());
+ Logger::warn(strf("Could not clone {}, not moving {} items as requested.", friendlyName(), takeCount).c_str());
}
}
diff --git a/source/game/StarItemDatabase.cpp b/source/game/StarItemDatabase.cpp
index 4012a20..dfeddfd 100644
--- a/source/game/StarItemDatabase.cpp
+++ b/source/game/StarItemDatabase.cpp
@@ -212,7 +212,7 @@ ItemPtr ItemDatabase::item(ItemDescriptor descriptor, Maybe<float> level, Maybe<
try {
item = createItem(m_items.get(descriptor.name()).type, itemConfig(descriptor.name(), descriptor.parameters(), level, seed));
} catch (std::exception const& e) {
- Logger::error("Could not instantiate item '%s'. %s", descriptor, outputException(e, false));
+ Logger::error("Could not instantiate item '{}'. {}", descriptor, outputException(e, false));
item = createItem(m_items.get("perfectlygenericitem").type, itemConfig("perfectlygenericitem", {}, {}));
}
item->setCount(descriptor.count());
@@ -350,7 +350,7 @@ ItemRecipe ItemDatabase::parseRecipe(Json const& config) const {
res.matchInputParameters = config.getBool("matchInputParameters", false);
} catch (JsonException const& e) {
- throw RecipeException(strf("Recipe missing required ingredient: %s", outputException(e, false)));
+ throw RecipeException(strf("Recipe missing required ingredient: {}", outputException(e, false)));
}
return res;
@@ -476,14 +476,14 @@ ItemPtr ItemDatabase::createItem(ItemType type, ItemConfig const& config) {
} else if (type == ItemType::AugmentItem) {
return make_shared<AugmentItem>(config.config, config.directory, config.parameters);
} else {
- throw ItemException(strf("Unknown item type %s", (int)type));
+ throw ItemException(strf("Unknown item type {}", (int)type));
}
}
ItemDatabase::ItemData const& ItemDatabase::itemData(String const& name) const {
if (auto p = m_items.ptr(name))
return *p;
- throw ItemException::format("No such item '%s'", name);
+ throw ItemException::format("No such item '{}'", name);
}
ItemRecipe ItemDatabase::makeRecipe(List<ItemDescriptor> inputs, ItemDescriptor output, float duration, StringSet groups) const {
@@ -515,11 +515,11 @@ void ItemDatabase::addItemSet(ItemType type, String const& extension) {
data.agingScripts = data.agingScripts.transformed(bind(&AssetPath::relativeTo, data.directory, _1));
} catch (std::exception const& e) {
- throw ItemException(strf("Could not load item asset %s", file), e);
+ throw ItemException(strf("Could not load item asset {}", file), e);
}
if (m_items.contains(data.name))
- throw ItemException(strf("Duplicate item name '%s' found", data.name));
+ throw ItemException(strf("Duplicate item name '{}' found", data.name));
m_items[data.name] = data;
}
@@ -538,7 +538,7 @@ void ItemDatabase::addObjectDropItem(String const& objectPath, Json const& objec
JsonObject customConfig = objectConfig.toObject();
if (!customConfig.contains("inventoryIcon")) {
customConfig["inventoryIcon"] = assets->json("/objects/defaultParameters.config:missingIcon");
- Logger::warn(strf("Missing inventoryIcon for %s, using default", data.name).c_str());
+ Logger::warn(strf("Missing inventoryIcon for {}, using default", data.name).c_str());
}
customConfig["itemName"] = data.name;
if (!customConfig.contains("tooltipKind"))
@@ -555,7 +555,7 @@ void ItemDatabase::addObjectDropItem(String const& objectPath, Json const& objec
data.customConfig = move(customConfig);
if (m_items.contains(data.name))
- throw ItemException(strf("Object drop '%s' shares name with existing item", data.name));
+ throw ItemException(strf("Object drop '{}' shares name with existing item", data.name));
m_items[data.name] = move(data);
}
@@ -617,7 +617,7 @@ void ItemDatabase::scanRecipes() {
try {
m_recipes.add(parseRecipe(assets->json(file)));
} catch (std::exception const& e) {
- Logger::error("Could not load recipe %s: %s", file, outputException(e, false));
+ Logger::error("Could not load recipe {}: {}", file, outputException(e, false));
}
}
}
@@ -629,7 +629,7 @@ void ItemDatabase::addBlueprints() {
auto baseDesc = recipe.output;
auto baseItem = item(baseDesc);
- String blueprintName = strf("%s-recipe", baseItem->name());
+ String blueprintName = strf("{}-recipe", baseItem->name());
if (m_items.contains(blueprintName))
continue;
@@ -666,7 +666,7 @@ void ItemDatabase::addBlueprints() {
m_items[blueprintData.name] = blueprintData;
} catch (std::exception const& e) {
- Logger::error("Could not create blueprint item from recipe: %s", outputException(e, false));
+ Logger::error("Could not create blueprint item from recipe: {}", outputException(e, false));
}
}
}
@@ -677,9 +677,9 @@ void ItemDatabase::addCodexes() {
auto codexDatabase = Root::singleton().codexDatabase();
for (auto const& codexPair : codexDatabase->codexes()) {
- String codexItemName = strf("%s-codex", codexPair.second->id());
+ String codexItemName = strf("{}-codex", codexPair.second->id());
if (m_items.contains(codexItemName)) {
- Logger::warn("Couldn't create codex item %s because an item with that name is already defined", codexItemName);
+ Logger::warn("Couldn't create codex item {} because an item with that name is already defined", codexItemName);
continue;
}
@@ -701,7 +701,7 @@ void ItemDatabase::addCodexes() {
m_items[codexItemName] = codexItemData;
} catch (std::exception const& e) {
- Logger::error("Could not create item for codex %s: %s", codexPair.second->id(), outputException(e, false));
+ Logger::error("Could not create item for codex {}: {}", codexPair.second->id(), outputException(e, false));
}
}
}
diff --git a/source/game/StarItemDescriptor.cpp b/source/game/StarItemDescriptor.cpp
index 4621de5..81f1464 100644
--- a/source/game/StarItemDescriptor.cpp
+++ b/source/game/StarItemDescriptor.cpp
@@ -149,7 +149,7 @@ DataStream& operator<<(DataStream& ds, ItemDescriptor const& itemDescriptor) {
}
std::ostream& operator<<(std::ostream& os, ItemDescriptor const& descriptor) {
- format(os, "[%s, %s, %s]", descriptor.m_name, descriptor.m_count, descriptor.m_parameters);
+ format(os, "[{}, {}, {}]", descriptor.m_name, descriptor.m_count, descriptor.m_parameters);
return os;
}
diff --git a/source/game/StarLiquidsDatabase.cpp b/source/game/StarLiquidsDatabase.cpp
index e0bcd0c..3161da7 100644
--- a/source/game/StarLiquidsDatabase.cpp
+++ b/source/game/StarLiquidsDatabase.cpp
@@ -41,7 +41,7 @@ LiquidsDatabase::LiquidsDatabase() {
unsigned id = liquidConfig.getUInt("liquidId");
if (id != (LiquidId)id)
- throw LiquidException(strf("Liquid id %s does not fall in the valid range, wrapped to %s\n", id, (LiquidId)id));
+ throw LiquidException(strf("Liquid id {} does not fall in the valid range, wrapped to {}\n", id, (LiquidId)id));
auto entry = make_shared<LiquidSettings>();
entry->id = (LiquidId)id;
@@ -77,7 +77,7 @@ LiquidsDatabase::LiquidsDatabase() {
interactionResult = makeRight<LiquidId>(*liquidResult);
else
throw LiquidException::format(
- "Neither resultMaterial or resultLiquid specified in liquid interaction of liquid %d", entry->id);
+ "Neither resultMaterial or resultLiquid specified in liquid interaction of liquid {}", entry->id);
entry->interactions[liquid] = interactionResult;
}
@@ -85,7 +85,7 @@ LiquidsDatabase::LiquidsDatabase() {
m_settings.set(entry->id, entry);
m_liquidNames.add(entry->name, entry->id);
} catch (StarException const& e) {
- throw LiquidException(strf("Error loading liquid file %s", file), e);
+ throw LiquidException(strf("Error loading liquid file {}", file), e);
}
}
}
@@ -111,7 +111,7 @@ String LiquidsDatabase::liquidName(LiquidId liquidId) const {
return "empty";
else if (auto settings = liquidSettings(liquidId))
return settings->name;
- throw LiquidException::format("invalid liquid id %d", liquidId);
+ throw LiquidException::format("invalid liquid id {}", liquidId);
}
String LiquidsDatabase::liquidDescription(LiquidId liquidId, String const& species) const {
@@ -119,8 +119,8 @@ String LiquidsDatabase::liquidDescription(LiquidId liquidId, String const& speci
return String();
else if (auto settings = liquidSettings(liquidId))
return settings->descriptions.getString(
- strf("%sDescription", species), settings->descriptions.getString("description"));
- throw LiquidException::format("invalid liquid id %d", liquidId);
+ strf("{}Description", species), settings->descriptions.getString("description"));
+ throw LiquidException::format("invalid liquid id {}", liquidId);
}
String LiquidsDatabase::liquidDescription(LiquidId liquidId) const {
@@ -128,7 +128,7 @@ String LiquidsDatabase::liquidDescription(LiquidId liquidId) const {
return String();
else if (auto settings = liquidSettings(liquidId))
return settings->descriptions.getString("description");
- throw LiquidException::format("invalid liquid id %d", liquidId);
+ throw LiquidException::format("invalid liquid id {}", liquidId);
}
Maybe<String> LiquidsDatabase::liquidPath(LiquidId liquidId) const {
diff --git a/source/game/StarMaterialDatabase.cpp b/source/game/StarMaterialDatabase.cpp
index fbfe4cc..abb49ad 100644
--- a/source/game/StarMaterialDatabase.cpp
+++ b/source/game/StarMaterialDatabase.cpp
@@ -34,16 +34,16 @@ MaterialDatabase::MaterialDatabase() {
for (auto metaMaterial : metaMaterialConfig.iterateArray()) {
auto matName = "metamaterial:" + metaMaterial.getString("name");
if (isMaterialName(matName)) {
- Logger::info("Metamaterial '%s' has duplicate material name!", matName);
+ Logger::info("Metamaterial '{}' has duplicate material name!", matName);
continue;
}
MaterialId matId = metaMaterial.getUInt("materialId");
if (isRealMaterial(matId) || matId >= FirstEngineMetaMaterialId) {
- Logger::info("Material id %s for metamaterial '%s' does not fall within the valid range!", matId, matName);
+ Logger::info("Material id {} for metamaterial '{}' does not fall within the valid range!", matId, matName);
continue;
} else if (containsMetaMaterial(matId)) {
- Logger::info("Material id %s for metamaterial '%s' conflicts with another metamaterial id!", matId, matName);
+ Logger::info("Material id {} for metamaterial '{}' conflicts with another metamaterial id!", matId, matName);
continue;
}
@@ -117,13 +117,13 @@ MaterialDatabase::MaterialDatabase() {
material.blocksLiquidFlow = matConfig.getBool("blocksLiquidFlow", isSolidColliding(material.collisionKind));
if (material.id != materialId || !isRealMaterial(material.id))
- throw MaterialException(strf("Material id %s does not fall in the valid range\n", materialId));
+ throw MaterialException(strf("Material id {} does not fall in the valid range\n", materialId));
if (containsMaterial(material.id))
- throw MaterialException(strf("Duplicate material id %s found for material %s", material.id, material.name));
+ throw MaterialException(strf("Duplicate material id {} found for material {}", material.id, material.name));
if (isMaterialName(material.name))
- throw MaterialException(strf("Duplicate material name '%s' found", material.name));
+ throw MaterialException(strf("Duplicate material name '{}' found", material.name));
setMaterial(material.id, material);
@@ -136,7 +136,7 @@ MaterialDatabase::MaterialDatabase() {
m_liquidMaterialInteractions[{liquidId, material.id}] = interaction;
}
} catch (StarException const& e) {
- throw MaterialException(strf("Error loading material file %s", file), e);
+ throw MaterialException(strf("Error loading material file {}", file), e);
}
}
@@ -187,13 +187,13 @@ MaterialDatabase::MaterialDatabase() {
modConfig.optUInt("harvestLevel"));
if (modId != mod.id || !isRealMod(mod.id))
- throw MaterialException(strf("Mod id %s does not fall in the valid range\n", mod.id));
+ throw MaterialException(strf("Mod id {} does not fall in the valid range\n", mod.id));
if (containsMod(mod.id))
- throw MaterialException(strf("Duplicate mod id %s found for mod %s", mod.id, mod.name));
+ throw MaterialException(strf("Duplicate mod id {} found for mod {}", mod.id, mod.name));
if (m_modIndex.contains(mod.name) || m_metaModIndex.hasLeftValue(mod.name))
- throw MaterialException(strf("Duplicate mod name '%s' found", mod.name));
+ throw MaterialException(strf("Duplicate mod name '{}' found", mod.name));
setMod(mod.id, mod);
m_modIndex[mod.name] = mod.id;
@@ -207,7 +207,7 @@ MaterialDatabase::MaterialDatabase() {
m_liquidModInteractions[{liquidId, mod.id}] = interaction;
}
} catch (StarException const& e) {
- throw MaterialException(strf("Error loading mod file %s", file), e);
+ throw MaterialException(strf("Error loading mod file {}", file), e);
}
}
@@ -266,7 +266,7 @@ Maybe<Json> MaterialDatabase::materialConfig(MaterialId materialId) const {
String MaterialDatabase::materialDescription(MaterialId materialNumber, String const& species) const {
auto material = m_materials[materialNumber];
return material->descriptions.getString(
- strf("%sDescription", species), material->descriptions.getString("description"));
+ strf("{}Description", species), material->descriptions.getString("description"));
}
String MaterialDatabase::materialDescription(MaterialId materialNumber) const {
@@ -331,7 +331,7 @@ Maybe<Json> MaterialDatabase::modConfig(ModId mod) const {
String MaterialDatabase::modDescription(ModId modId, String const& species) const {
auto mod = m_mods[modId];
- return mod->descriptions.getString(strf("%sDescription", species), mod->descriptions.getString("description"));
+ return mod->descriptions.getString(strf("{}Description", species), mod->descriptions.getString("description"));
}
String MaterialDatabase::modDescription(ModId modId) const {
@@ -554,21 +554,21 @@ void MaterialDatabase::setMod(ModId modId, ModInfo info) {
shared_ptr<MaterialDatabase::MetaMaterialInfo const> const& MaterialDatabase::getMetaMaterialInfo(MaterialId materialId) const {
if (!containsMetaMaterial(materialId))
- throw MaterialException(strf("No such metamaterial id: %s\n", materialId));
+ throw MaterialException(strf("No such metamaterial id: {}\n", materialId));
else
return m_metaMaterials[metaMaterialIndex(materialId)];
}
shared_ptr<MaterialDatabase::MaterialInfo const> const& MaterialDatabase::getMaterialInfo(MaterialId materialId) const {
if (materialId >= m_materials.size() || !m_materials[materialId])
- throw MaterialException(strf("No such material id: %s\n", materialId));
+ throw MaterialException(strf("No such material id: {}\n", materialId));
else
return m_materials[materialId];
}
shared_ptr<MaterialDatabase::ModInfo const> const& MaterialDatabase::getModInfo(ModId modId) const {
if (modId >= m_mods.size() || !m_mods[modId])
- throw MaterialException(strf("No such modId id: %s\n", modId));
+ throw MaterialException(strf("No such modId id: {}\n", modId));
else
return m_mods[modId];
}
diff --git a/source/game/StarMaterialRenderProfile.cpp b/source/game/StarMaterialRenderProfile.cpp
index 39012f1..a763f61 100644
--- a/source/game/StarMaterialRenderProfile.cpp
+++ b/source/game/StarMaterialRenderProfile.cpp
@@ -30,7 +30,7 @@ MaterialRenderMatchList parseMaterialRenderMatchList(Json const& matchSpec, Rule
MaterialMatchPoint matchPoint;
matchPoint.position = jsonToVec2I(matchPointConfig.get(0));
if (abs(matchPoint.position[0]) > MaterialRenderProfileMaxNeighborDistance || abs(matchPoint.position[1]) > MaterialRenderProfileMaxNeighborDistance)
- throw MaterialRenderProfileException(strf("Match position %s outside of maximum rule distance %s",
+ throw MaterialRenderProfileException(strf("Match position {} outside of maximum rule distance {}",
matchPoint.position, MaterialRenderProfileMaxNeighborDistance));
matchPoint.rule = ruleMap.get(matchPointConfig.getString(1));
match->matchPoints.append(move(matchPoint));
@@ -62,10 +62,10 @@ String MaterialRenderProfile::pieceImage(String const& pieceName, unsigned varia
String texture = piece->texture;
if (hueShift != MaterialHue())
- texture = strf("%s?hueshift=%s", texture, materialHueToDegrees(hueShift));
+ texture = strf("{}?hueshift={}", texture, materialHueToDegrees(hueShift));
auto const& rect = piece->variants.get(colorVariant).wrap(variant);
- return strf("%s?crop=%s;%s;%s;%s", texture, rect.xMin(), rect.yMin(), rect.xMax(), rect.yMax());
+ return strf("{}?crop={};{};{};{}", texture, rect.xMin(), rect.yMin(), rect.xMax(), rect.yMax());
}
pair<String, Vec2F> const& MaterialRenderProfile::damageImage(float damageLevel, TileDamageType damageType) const {
diff --git a/source/game/StarMicroDungeon.cpp b/source/game/StarMicroDungeon.cpp
index 646e8b1..aefdbb9 100644
--- a/source/game/StarMicroDungeon.cpp
+++ b/source/game/StarMicroDungeon.cpp
@@ -42,7 +42,7 @@ Maybe<pair<List<RectI>, Set<Vec2I>>> MicroDungeonFactory::generate(RectI const&
auto anchorPart = dungeonGenerator.pickAnchor();
if (!anchorPart) {
- Logger::debug("No valid anchor piece found for microdungeon at %s, skipping", position);
+ Logger::debug("No valid anchor piece found for microdungeon at {}, skipping", position);
return {};
}
@@ -71,7 +71,7 @@ Maybe<pair<List<RectI>, Set<Vec2I>>> MicroDungeonFactory::generate(RectI const&
}
}
} catch (std::exception const& e) {
- throw DungeonException(strf("Error generating microdungeon named '%s'", dungeonGenerator.definition()->name()), e);
+ throw DungeonException(strf("Error generating microdungeon named '{}'", dungeonGenerator.definition()->name()), e);
}
return {};
diff --git a/source/game/StarMonster.cpp b/source/game/StarMonster.cpp
index c8b69bf..99b7e49 100644
--- a/source/game/StarMonster.cpp
+++ b/source/game/StarMonster.cpp
@@ -557,7 +557,7 @@ LuaCallbacks Monster::makeMonsterCallbacks() {
});
callbacks.registerCallback("seed", [this]() {
- return strf("%d", m_monsterVariant.seed);
+ return strf("{}", m_monsterVariant.seed);
});
callbacks.registerCallback("uniqueParameters", [this]() {
diff --git a/source/game/StarMonsterDatabase.cpp b/source/game/StarMonsterDatabase.cpp
index 0fbc796..4f6359f 100644
--- a/source/game/StarMonsterDatabase.cpp
+++ b/source/game/StarMonsterDatabase.cpp
@@ -27,7 +27,7 @@ MonsterDatabase::MonsterDatabase() {
String typeName = config.getString("type");
if (m_monsterTypes.contains(typeName))
- throw MonsterException(strf("Repeat monster type name '%s'", typeName));
+ throw MonsterException(strf("Repeat monster type name '{}'", typeName));
MonsterType& monsterType = m_monsterTypes[typeName];
@@ -62,7 +62,7 @@ MonsterDatabase::MonsterDatabase() {
}
} catch (StarException const& e) {
- throw MonsterException(strf("Error loading monster type '%s'", file), e);
+ throw MonsterException(strf("Error loading monster type '{}'", file), e);
}
}
@@ -83,11 +83,11 @@ MonsterDatabase::MonsterDatabase() {
auto& partMap = m_partDirectory[part.category][part.type];
if (partMap.contains(part.name))
- throw MonsterException(strf("Repeat monster part name '%s' for category '%s'", part.name, part.category));
+ throw MonsterException(strf("Repeat monster part name '{}' for category '{}'", part.name, part.category));
else
partMap[part.name] = part;
} catch (StarException const& e) {
- throw MonsterException(strf("Error loading monster part '%s'", file), e);
+ throw MonsterException(strf("Error loading monster part '{}'", file), e);
}
}
@@ -107,11 +107,11 @@ MonsterDatabase::MonsterDatabase() {
skill.animationParameters = config.get("animationParameters", JsonObject());
if (m_skills.contains(skill.name))
- throw MonsterException(strf("Repeat monster skill name '%s'", skill.name));
+ throw MonsterException(strf("Repeat monster skill name '{}'", skill.name));
else
m_skills[skill.name] = skill;
} catch (StarException const& e) {
- throw MonsterException(strf("Error loading monster skill '%s'", file), e);
+ throw MonsterException(strf("Error loading monster skill '{}'", file), e);
}
}
@@ -123,7 +123,7 @@ MonsterDatabase::MonsterDatabase() {
auto paletteName = config.getString("name");
if (m_colorSwaps.contains(paletteName))
- throw MonsterException(strf("Duplicate monster colors name '%s'", paletteName));
+ throw MonsterException(strf("Duplicate monster colors name '{}'", paletteName));
ColorReplaceMap colorSwaps;
for (auto const& swapSet : config.getArray("swaps")) {
@@ -134,7 +134,7 @@ MonsterDatabase::MonsterDatabase() {
m_colorSwaps[paletteName].append(colorSwaps);
}
} catch (StarException const& e) {
- throw MonsterException(strf("Error loading monster colors '%s'", file), e);
+ throw MonsterException(strf("Error loading monster colors '{}'", file), e);
}
}
}
@@ -255,7 +255,7 @@ ColorReplaceMap MonsterDatabase::colorSwap(String const& setName, uint64_t seed)
if (m_colorSwaps.contains(setName))
return staticRandomFrom(m_colorSwaps.get(setName), seed);
else {
- Logger::error("Monster colors '%s' not found!", setName);
+ Logger::error("Monster colors '{}' not found!", setName);
return staticRandomFrom(m_colorSwaps.get("default"), seed);
}
}
diff --git a/source/game/StarNameGenerator.cpp b/source/game/StarNameGenerator.cpp
index 44f1512..6dd2350 100644
--- a/source/game/StarNameGenerator.cpp
+++ b/source/game/StarNameGenerator.cpp
@@ -14,12 +14,12 @@ PatternedNameGenerator::PatternedNameGenerator() {
auto sourceConfig = assets->json(file);
if (m_markovSources.contains(sourceConfig.getString("name")))
- throw NameGeneratorException::format("Duplicate name source '%s', config file '%s'", sourceConfig.getString("name"), file);
+ throw NameGeneratorException::format("Duplicate name source '{}', config file '{}'", sourceConfig.getString("name"), file);
m_markovSources.insert(sourceConfig.getString("name"), makeMarkovSource(sourceConfig.getUInt("prefixSize", 1),
sourceConfig.getUInt("endSize", 1), jsonToStringList(sourceConfig.get("sourceNames"))));
} catch (std::exception const& e) {
- throw NameGeneratorException(strf("Error reading name source config %s", file), e);
+ throw NameGeneratorException(strf("Error reading name source config {}", file), e);
}
}
@@ -82,7 +82,7 @@ String PatternedNameGenerator::processRule(JsonArray const& rule, RandomSource&
result += entry.toString();
} else if (mode == "markov") {
if (!m_markovSources.contains(meta.getString("source")))
- throw NameGeneratorException::format("Unknown name source '%s'", meta.getString("source"));
+ throw NameGeneratorException::format("Unknown name source '{}'", meta.getString("source"));
auto source = m_markovSources.get(meta.getString("source"));
auto lengthRange = meta.getArray("targetLength");
@@ -104,7 +104,7 @@ String PatternedNameGenerator::processRule(JsonArray const& rule, RandomSource&
result += piece;
} else
- throw StarException::format("Unknown mode: %s", mode);
+ throw StarException::format("Unknown mode: {}", mode);
if (titleCase)
result = result.titleCase();
diff --git a/source/game/StarNetPacketSocket.cpp b/source/game/StarNetPacketSocket.cpp
index 392f2d9..f6ebce0 100644
--- a/source/game/StarNetPacketSocket.cpp
+++ b/source/game/StarNetPacketSocket.cpp
@@ -194,7 +194,7 @@ List<PacketPtr> TcpPacketSocket::receivePackets() {
}
if (packetSize > PacketSizeLimit)
- throw IOException::format("Packet size %s exceeds maximum allowed packet size!", packetSize);
+ throw IOException::format("Packet size {} exceeds maximum allowed packet size!", packetSize);
if (packetSize > ds.size() - ds.pos())
break;
@@ -215,7 +215,7 @@ List<PacketPtr> TcpPacketSocket::receivePackets() {
m_inputBuffer = ds.readBytes(ds.size() - ds.pos());
}
} catch (IOException const& e) {
- Logger::warn("I/O error in TcpPacketSocket::readPackets, closing: %s", outputException(e, false));
+ Logger::warn("I/O error in TcpPacketSocket::readPackets, closing: {}", outputException(e, false));
m_inputBuffer.clear();
m_socket->shutdown();
}
@@ -243,9 +243,9 @@ bool TcpPacketSocket::writeData() {
m_outputBuffer.trimLeft(writtenAmount);
}
} catch (SocketClosedException const& e) {
- Logger::debug("TcpPacketSocket socket closed: %s", outputException(e, false));
+ Logger::debug("TcpPacketSocket socket closed: {}", outputException(e, false));
} catch (IOException const& e) {
- Logger::warn("I/O error in TcpPacketSocket::sendData: %s", outputException(e, false));
+ Logger::warn("I/O error in TcpPacketSocket::sendData: {}", outputException(e, false));
m_socket->shutdown();
}
return dataSent;
@@ -263,9 +263,9 @@ bool TcpPacketSocket::readData() {
m_inputBuffer.append(readBuffer, readAmount);
}
} catch (SocketClosedException const& e) {
- Logger::debug("TcpPacketSocket socket closed: %s", outputException(e, false));
+ Logger::debug("TcpPacketSocket socket closed: {}", outputException(e, false));
} catch (IOException const& e) {
- Logger::warn("I/O error in TcpPacketSocket::receiveData: %s", outputException(e, false));
+ Logger::warn("I/O error in TcpPacketSocket::receiveData: {}", outputException(e, false));
m_socket->shutdown();
}
return dataReceived;
@@ -352,7 +352,7 @@ List<PacketPtr> P2PPacketSocket::receivePackets() {
} while (!packetStream.atEnd());
}
} catch (IOException const& e) {
- Logger::warn("I/O error in P2PPacketSocket::readPackets, closing: %s", outputException(e, false));
+ Logger::warn("I/O error in P2PPacketSocket::readPackets, closing: {}", outputException(e, false));
m_socket.reset();
}
return packets;
diff --git a/source/game/StarNetPackets.cpp b/source/game/StarNetPackets.cpp
index e6c856b..edd1a14 100644
--- a/source/game/StarNetPackets.cpp
+++ b/source/game/StarNetPackets.cpp
@@ -151,7 +151,7 @@ PacketPtr createPacket(PacketType type) {
case PacketType::SystemShipDestroy: return make_shared<SystemShipDestroyPacket>();
case PacketType::SystemObjectSpawn: return make_shared<SystemObjectSpawnPacket>();
default:
- throw StarPacketException(strf("Unrecognized packet type %s", (unsigned int)type));
+ throw StarPacketException(strf("Unrecognized packet type {}", (unsigned int)type));
}
}
diff --git a/source/game/StarNetworkedAnimator.cpp b/source/game/StarNetworkedAnimator.cpp
index 718073f..065ca31 100644
--- a/source/game/StarNetworkedAnimator.cpp
+++ b/source/game/StarNetworkedAnimator.cpp
@@ -577,7 +577,7 @@ List<pair<Drawable, float>> NetworkedAnimator::drawablesWithZLevel(Vec2F const&
} else if (effect.type == "directive") {
baseProcessingDirectives.append(effect.directives);
} else {
- throw NetworkedAnimatorException(strf("No such NetworkedAnimator effect type '%s'", effect.type));
+ throw NetworkedAnimatorException(strf("No such NetworkedAnimator effect type '{}'", effect.type));
}
}
}
diff --git a/source/game/StarNpcDatabase.cpp b/source/game/StarNpcDatabase.cpp
index dd0a5fc..8f2e820 100644
--- a/source/game/StarNpcDatabase.cpp
+++ b/source/game/StarNpcDatabase.cpp
@@ -25,12 +25,12 @@ NpcDatabase::NpcDatabase() {
String typeName = config.getString("type");
if (m_npcTypes.contains(typeName))
- throw NpcException(strf("Repeat npc type name '%s'", typeName));
+ throw NpcException(strf("Repeat npc type name '{}'", typeName));
m_npcTypes[typeName] = config;
} catch (StarException const& e) {
- throw NpcException(strf("Error loading npc type '%s'", file), e);
+ throw NpcException(strf("Error loading npc type '{}'", file), e);
}
}
}
diff --git a/source/game/StarObject.cpp b/source/game/StarObject.cpp
index dc19d74..1dfc89d 100644
--- a/source/game/StarObject.cpp
+++ b/source/game/StarObject.cpp
@@ -483,7 +483,7 @@ void Object::destroy(RenderCallback* renderCallback) {
}
}
} catch (StarException const& e) {
- Logger::warn("Invalid dropID in entity death. %s", outputException(e, false));
+ Logger::warn("Invalid dropID in entity death. {}", outputException(e, false));
}
}
@@ -543,7 +543,7 @@ Maybe<String> Object::inspectionLogName() const {
Maybe<String> Object::inspectionDescription(String const& species) const {
return configValue("inspectionDescription").optString()
- .orMaybe(configValue(strf("%sDescription", species)).optString())
+ .orMaybe(configValue(strf("{}Description", species)).optString())
.value(description());
}
diff --git a/source/game/StarObjectDatabase.cpp b/source/game/StarObjectDatabase.cpp
index 11c45c7..4c9a968 100644
--- a/source/game/StarObjectDatabase.cpp
+++ b/source/game/StarObjectDatabase.cpp
@@ -239,7 +239,7 @@ List<ObjectOrientationPtr> ObjectDatabase::parseOrientations(String const& path,
for (auto space : orientation->spaces)
orientation->anchors.append({TileLayer::Background, space, tilled, soil, anchorMaterial});
} else {
- throw ObjectException(strf("Unknown anchor type: %s", anchorType));
+ throw ObjectException(strf("Unknown anchor type: {}", anchorType));
}
}
@@ -315,11 +315,11 @@ ObjectDatabase::ObjectDatabase() {
try {
String name = assets->json(file).getString("objectName");
if (m_paths.contains(name))
- Logger::error("Object %s defined twice, second time from %s", name, file);
+ Logger::error("Object {} defined twice, second time from {}", name, file);
else
m_paths[name] = file;
} catch (std::exception const& e) {
- Logger::error("Error loading object file %s: %s", file, outputException(e, true));
+ Logger::error("Error loading object file {}: {}", file, outputException(e, true));
}
}
}
@@ -345,7 +345,7 @@ ObjectConfigPtr ObjectDatabase::getConfig(String const& objectName) const {
[this](String const& objectName) -> ObjectConfigPtr {
if (auto path = m_paths.maybe(objectName))
return readConfig(*path);
- throw ObjectException(strf("No such object named '%s'", objectName));
+ throw ObjectException(strf("No such object named '{}'", objectName));
});
}
@@ -369,7 +369,7 @@ ObjectPtr ObjectDatabase::createObject(String const& objectName, Json const& par
} else if (config->type == "physics") {
return make_shared<PhysicsObject>(config, parameters);
} else {
- throw ObjectException(strf("Unknown objectType '%s' constructing object '%s'", config->type, objectName));
+ throw ObjectException(strf("Unknown objectType '{}' constructing object '{}'", config->type, objectName));
}
}
@@ -545,7 +545,7 @@ ObjectConfigPtr ObjectDatabase::readConfig(String const& path) {
return objectConfig;
} catch (std::exception const& e) {
- throw ObjectException::format("Error loading object '%s': %s", path, outputException(e, false));
+ throw ObjectException::format("Error loading object '{}': {}", path, outputException(e, false));
}
}
diff --git a/source/game/StarParallax.cpp b/source/game/StarParallax.cpp
index f895d83..63025ab 100644
--- a/source/game/StarParallax.cpp
+++ b/source/game/StarParallax.cpp
@@ -238,11 +238,11 @@ void Parallax::buildLayer(Json const& layerSettings, String const& kind) {
layer.addImageDirectives(layerSettings.getString("directives", ""));
if (isFoliage)
- layer.addImageDirectives(String(strf("hueshift=%s", m_parallaxTreeVariant->foliageHueShift)));
+ layer.addImageDirectives(String(strf("hueshift={}", m_parallaxTreeVariant->foliageHueShift)));
else if (isStem)
- layer.addImageDirectives(String(strf("hueshift=%s", m_parallaxTreeVariant->stemHueShift)));
+ layer.addImageDirectives(String(strf("hueshift={}", m_parallaxTreeVariant->stemHueShift)));
else if (!layerSettings.getBool("nohueshift", false))
- layer.addImageDirectives(String(strf("hueshift=%s", m_hueShift)));
+ layer.addImageDirectives(String(strf("hueshift={}", m_hueShift)));
layer.fadePercent = layerSettings.getFloat("fadePercent", 0);
diff --git a/source/game/StarParticleDatabase.cpp b/source/game/StarParticleDatabase.cpp
index 91315ca..bade6b5 100644
--- a/source/game/StarParticleDatabase.cpp
+++ b/source/game/StarParticleDatabase.cpp
@@ -28,7 +28,7 @@ ParticleDatabase::ParticleDatabase() {
for (auto file : files) {
auto particleConfig = make_shared<ParticleConfig>(assets->json(file));
if (m_configs.contains(particleConfig->kind()))
- throw StarException(strf("Duplicate particle asset kind Name %s. configfile %s", particleConfig->kind(), file));
+ throw StarException(strf("Duplicate particle asset kind Name {}. configfile {}", particleConfig->kind(), file));
m_configs[particleConfig->kind()] = particleConfig;
}
}
@@ -36,7 +36,7 @@ ParticleDatabase::ParticleDatabase() {
ParticleConfigPtr ParticleDatabase::config(String const& kind) const {
auto k = kind.toLower();
if (!m_configs.contains(k))
- throw StarException(strf("Unknown particle definition with kind %s.", kind));
+ throw StarException(strf("Unknown particle definition with kind {}.", kind));
return m_configs.get(k);
}
diff --git a/source/game/StarPlant.cpp b/source/game/StarPlant.cpp
index f6a366b..4ba8ada 100644
--- a/source/game/StarPlant.cpp
+++ b/source/game/StarPlant.cpp
@@ -98,7 +98,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
{
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", baseFile, config.stemHueShift);
+ piece.image = strf("{}?hueshift={}", baseFile, config.stemHueShift);
piece.offset = Vec2F(xOffset, yOffset);
piece.segmentIdx = segment;
piece.structuralSegment = true;
@@ -123,7 +123,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
AssetPath::relativeTo(config.foliageDirectory, baseLeavesSettings.get("image").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", baseLeavesFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", baseLeavesFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -138,7 +138,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String baseLeavesBackFile =
AssetPath::relativeTo(config.foliageDirectory, baseLeavesSettings.get("backimage").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", baseLeavesBackFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", baseLeavesBackFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -184,7 +184,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
{
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", middleFile, config.stemHueShift);
+ piece.image = strf("{}?hueshift={}", middleFile, config.stemHueShift);
piece.offset = Vec2F(xOffset, yOffset);
piece.segmentIdx = segment;
piece.structuralSegment = true;
@@ -208,7 +208,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String trunkLeavesFile =
AssetPath::relativeTo(config.foliageDirectory, trunkLeavesSettings.get("image").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", trunkLeavesFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", trunkLeavesFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -223,7 +223,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String trunkLeavesBackFile =
AssetPath::relativeTo(config.foliageDirectory, trunkLeavesSettings.get("backimage").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", trunkLeavesBackFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", trunkLeavesBackFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -256,7 +256,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String branchFile = AssetPath::relativeTo(config.stemDirectory, branchSettings.get("image").toString());
{
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", branchFile, config.stemHueShift);
+ piece.image = strf("{}?hueshift={}", branchFile, config.stemHueShift);
piece.offset = Vec2F{xO, yO};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -281,7 +281,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String branchLeavesFile =
AssetPath::relativeTo(config.foliageDirectory, branchLeavesSettings.get("image").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", branchLeavesFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", branchLeavesFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -297,7 +297,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String branchLeavesBackFile =
AssetPath::relativeTo(config.foliageDirectory, branchLeavesSettings.get("backimage").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", branchLeavesBackFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", branchLeavesBackFile, config.foliageHueShift);
piece.offset = Vec2F{xOf, yOf};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -335,7 +335,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
String crownFile = AssetPath::relativeTo(config.stemDirectory, crownSettings.get("image").toString());
{
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", crownFile, config.stemHueShift);
+ piece.image = strf("{}?hueshift={}", crownFile, config.stemHueShift);
piece.offset = Vec2F{xOffset, yOffset};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -360,7 +360,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
AssetPath::relativeTo(config.foliageDirectory, crownLeavesSettings.get("image").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", crownLeavesFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", crownLeavesFile, config.foliageHueShift);
piece.offset = Vec2F{xO, yO};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -376,7 +376,7 @@ Plant::Plant(TreeVariant const& config, uint64_t seed) : Plant() {
AssetPath::relativeTo(config.foliageDirectory, crownLeavesSettings.get("backimage").toString());
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", crownLeavesBackFile, config.foliageHueShift);
+ piece.image = strf("{}?hueshift={}", crownLeavesBackFile, config.foliageHueShift);
piece.offset = Vec2F{xO, yO};
piece.segmentIdx = segment;
piece.structuralSegment = false;
@@ -455,7 +455,7 @@ Plant::Plant(GrassVariant const& config, uint64_t seed) : Plant() {
}
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", imageName, config.hueShift);
+ piece.image = strf("{}?hueshift={}", imageName, config.hueShift);
piece.offset = offset;
piece.segmentIdx = 0;
piece.structuralSegment = true;
@@ -494,7 +494,7 @@ Plant::Plant(BushVariant const& config, uint64_t seed) : Plant() {
{
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", shapeImageName, config.baseHueShift);
+ piece.image = strf("{}?hueshift={}", shapeImageName, config.baseHueShift);
piece.offset = offset;
piece.segmentIdx = 0;
piece.structuralSegment = true;
@@ -505,7 +505,7 @@ Plant::Plant(BushVariant const& config, uint64_t seed) : Plant() {
auto mod = rand.randValueFrom(shape.mods);
if (!mod.empty()) {
PlantPiece piece;
- piece.image = strf("%s?hueshift=%s", AssetPath::relativeTo(config.directory, mod), config.modHueShift);
+ piece.image = strf("{}?hueshift={}", AssetPath::relativeTo(config.directory, mod), config.modHueShift);
piece.offset = offset;
piece.segmentIdx = 0;
piece.structuralSegment = false;
@@ -774,7 +774,7 @@ void Plant::render(RenderCallback* renderCallback) {
auto particle = Root::singleton().particleDatabase()->particle(config);
particle.color.hueShift(hueshift);
if (!particle.string.empty()) {
- particle.string = strf("%s?hueshift=%s", particle.string, hueshift);
+ particle.string = strf("{}?hueshift={}", particle.string, hueshift);
particle.image = particle.string;
}
particle.position = {m_tileDamageX + Random::randf(), m_tileDamageY + Random::randf()};
diff --git a/source/game/StarPlantDatabase.cpp b/source/game/StarPlantDatabase.cpp
index 8d927af..4573634 100644
--- a/source/game/StarPlantDatabase.cpp
+++ b/source/game/StarPlantDatabase.cpp
@@ -175,7 +175,7 @@ Maybe<String> PlantDatabase::treeFoliageDirectory(String const& foliageName) con
TreeVariant PlantDatabase::buildTreeVariant(
String const& stemName, float stemHueShift, String const& foliageName, float foliageHueShift) const {
if (!m_treeStemConfigs.contains(stemName) || !m_treeFoliageConfigs.contains(foliageName))
- throw PlantDatabaseException::format("stemName '%s' or foliageName '%s' not found in plant database", stemName, foliageName);
+ throw PlantDatabaseException::format("stemName '{}' or foliageName '{}' not found in plant database", stemName, foliageName);
TreeVariant treeVariant;
@@ -216,7 +216,7 @@ TreeVariant PlantDatabase::buildTreeVariant(
TreeVariant PlantDatabase::buildTreeVariant(String const& stemName, float stemHueShift) const {
if (!m_treeStemConfigs.contains(stemName))
- throw PlantDatabaseException(strf("stemName '%s' not found in plant database", stemName));
+ throw PlantDatabaseException(strf("stemName '{}' not found in plant database", stemName));
TreeVariant treeVariant;
@@ -260,7 +260,7 @@ StringList PlantDatabase::grassNames(bool ceiling) const {
GrassVariant PlantDatabase::buildGrassVariant(String const& name, float hueShift) const {
if (!m_grassConfigs.contains(name))
- throw PlantDatabaseException(strf("grass '%s' not found in plant database", name));
+ throw PlantDatabaseException(strf("grass '{}' not found in plant database", name));
GrassVariant grassVariant;
auto config = m_grassConfigs.get(name);
@@ -302,7 +302,7 @@ StringList PlantDatabase::bushMods(String const& bushName) const {
BushVariant PlantDatabase::buildBushVariant(String const& bushName, float baseHueShift, String const& modName, float modHueShift) const {
if (!m_bushConfigs.contains(bushName))
- throw PlantDatabaseException(strf("bush '%s' not found in plant database", bushName));
+ throw PlantDatabaseException(strf("bush '{}' not found in plant database", bushName));
BushVariant bushVariant;
auto config = m_bushConfigs.get(bushName);
@@ -342,7 +342,7 @@ PlantPtr PlantDatabase::createPlant(TreeVariant const& treeVariant, uint64_t see
try {
return make_shared<Plant>(treeVariant, seed);
} catch (std::exception const& e) {
- throw PlantDatabaseException(strf("Error constructing plant from tree variant stem: %s foliage: %s", treeVariant.stemName, treeVariant.foliageName), e);
+ throw PlantDatabaseException(strf("Error constructing plant from tree variant stem: {} foliage: {}", treeVariant.stemName, treeVariant.foliageName), e);
}
}
@@ -350,7 +350,7 @@ PlantPtr PlantDatabase::createPlant(GrassVariant const& grassVariant, uint64_t s
try {
return make_shared<Plant>(grassVariant, seed);
} catch (std::exception const& e) {
- throw PlantDatabaseException(strf("Error constructing plant from grass variant name: %s", grassVariant.name), e);
+ throw PlantDatabaseException(strf("Error constructing plant from grass variant name: {}", grassVariant.name), e);
}
}
@@ -359,7 +359,7 @@ PlantPtr PlantDatabase::createPlant(BushVariant const& bushVariant, uint64_t see
return make_shared<Plant>(bushVariant, seed);
} catch (std::exception const& e) {
throw PlantDatabaseException(
- strf("Error constructing plant from bush variant name: %s mod: %s", bushVariant.bushName, bushVariant.modName),
+ strf("Error constructing plant from bush variant name: {} mod: {}", bushVariant.bushName, bushVariant.modName),
e);
}
}
diff --git a/source/game/StarPlatformerAStarTypes.hpp b/source/game/StarPlatformerAStarTypes.hpp
index 57b6927..90afbbd 100644
--- a/source/game/StarPlatformerAStarTypes.hpp
+++ b/source/game/StarPlatformerAStarTypes.hpp
@@ -98,7 +98,7 @@ inline bool operator==(Node const& a, Node const& b) {
}
inline std::ostream& operator<<(std::ostream& os, Node const& node) {
- return os << strf("Node{position = %s, velocity = %s}", node.position, node.velocity);
+ return os << strf("Node{position = {}, velocity = {}}", node.position, node.velocity);
}
inline std::ostream& operator<<(std::ostream& os, Action action) {
@@ -106,7 +106,7 @@ inline std::ostream& operator<<(std::ostream& os, Action action) {
}
inline std::ostream& operator<<(std::ostream& os, Edge const& edge) {
- return os << strf("Edge{cost = %f, action = %s, jumpVelocity = %s, source = %s, target = %s}",
+ return os << strf("Edge{cost = %f, action = {}, jumpVelocity = {}, source = {}, target = {}}",
edge.cost,
edge.action,
edge.jumpVelocity,
diff --git a/source/game/StarPlayer.cpp b/source/game/StarPlayer.cpp
index 3eb464b..be30cd4 100644
--- a/source/game/StarPlayer.cpp
+++ b/source/game/StarPlayer.cpp
@@ -102,7 +102,7 @@ Player::Player(PlayerConfigPtr config, Uuid uuid) {
m_techs = make_shared<PlayerTech>();
m_log = make_shared<PlayerLog>();
- m_description = strf("This %s seems to have nothing to say for %sself.",
+ m_description = strf("This {} seems to have nothing to say for {}self.",
m_identity.gender == Gender::Male ? "guy" : "gal",
m_identity.gender == Gender::Male ? "him" : "her");
@@ -2239,7 +2239,7 @@ void Player::queueRadioMessage(Json const& messageConfig, float delay) {
if (!message.portraitImage.empty() && message.portraitImage[0] != '/')
message.portraitImage = Root::singleton().aiDatabase()->portraitImage(species(), message.portraitImage);
} catch (RadioMessageDatabaseException const& e) {
- Logger::error("Couldn't queue radio message '%s': %s", messageConfig, e.what());
+ Logger::error("Couldn't queue radio message '{}': {}", messageConfig, e.what());
return;
}
diff --git a/source/game/StarPlayerCodexes.cpp b/source/game/StarPlayerCodexes.cpp
index 0391c5a..bb96130 100644
--- a/source/game/StarPlayerCodexes.cpp
+++ b/source/game/StarPlayerCodexes.cpp
@@ -15,7 +15,7 @@ PlayerCodexes::PlayerCodexes(Json const& variant) {
if (auto codex = Root::singleton().codexDatabase()->codex(pair.first)) {
m_codexes[pair.first] = CodexEntry{codex, pair.second};
} else {
- Logger::debug("Failed to load missing codex '%s'", pair.first);
+ Logger::debug("Failed to load missing codex '{}'", pair.first);
}
}
}
@@ -72,7 +72,7 @@ bool PlayerCodexes::markCodexUnread(String const& codexId) {
}
void PlayerCodexes::learnInitialCodexes(String const& playerSpecies) {
- for (auto codexId : jsonToStringList(Root::singleton().assets()->json(strf("/player.config:defaultCodexes.%s", playerSpecies))))
+ for (auto codexId : jsonToStringList(Root::singleton().assets()->json(strf("/player.config:defaultCodexes.{}", playerSpecies))))
learnCodex(codexId, true);
}
diff --git a/source/game/StarPlayerStorage.cpp b/source/game/StarPlayerStorage.cpp
index c899266..dfccc88 100644
--- a/source/game/StarPlayerStorage.cpp
+++ b/source/game/StarPlayerStorage.cpp
@@ -42,7 +42,7 @@ PlayerStorage::PlayerStorage(String const& storageDir) {
auto& playerCacheData = m_savedPlayersCache[uuid];
playerCacheData = entityFactory->loadVersionedJson(VersionedJson::readFile(filename), EntityType::Player);
} catch (std::exception const& e) {
- Logger::error("Error loading player file, ignoring! %s : %s", filename, outputException(e, false));
+ Logger::error("Error loading player file, ignoring! {} : {}", filename, outputException(e, false));
}
}
}
@@ -59,9 +59,9 @@ PlayerStorage::PlayerStorage(String const& storageDir) {
auto entityFactory = Root::singleton().entityFactory();
auto player = as<Player>(entityFactory->diskLoadEntity(EntityType::Player, entry.second));
if (player->uuid() != entry.first)
- throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '%s'", entry.first.hex()));
+ throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '{}'", entry.first.hex()));
} catch (StarException const& e) {
- Logger::error("Failed to valid player with uuid %s : %s", entry.first.hex(), outputException(e, true));
+ Logger::error("Failed to valid player with uuid {} : {}", entry.first.hex(), outputException(e, true));
it.remove();
}
}
@@ -77,7 +77,7 @@ PlayerStorage::PlayerStorage(String const& storageDir) {
m_savedPlayersCache.toBack(Uuid(uuid.toString()));
}
} catch (std::exception const& e) {
- Logger::warn("Error loading player storage metadata file, resetting: %s", outputException(e, false));
+ Logger::warn("Error loading player storage metadata file, resetting: {}", outputException(e, false));
}
}
@@ -111,24 +111,24 @@ void PlayerStorage::savePlayer(PlayerPtr const& player) {
if (playerCacheData != newPlayerData) {
playerCacheData = newPlayerData;
VersionedJson versionedJson = entityFactory->storeVersionedJson(EntityType::Player, playerCacheData);
- VersionedJson::writeFile(versionedJson, File::relativeTo(m_storageDirectory, strf("%s.player", uuid.hex())));
+ VersionedJson::writeFile(versionedJson, File::relativeTo(m_storageDirectory, strf("{}.player", uuid.hex())));
}
}
PlayerPtr PlayerStorage::loadPlayer(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
- throw PlayerException(strf("No such stored player with uuid '%s'", uuid.hex()));
+ throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
auto entityFactory = Root::singleton().entityFactory();
auto const& playerCacheData = m_savedPlayersCache.get(uuid);
try {
auto player = convert<Player>(entityFactory->diskLoadEntity(EntityType::Player, playerCacheData));
if (player->uuid() != uuid)
- throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '%s'", uuid.hex()));
+ throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '{}'", uuid.hex()));
return player;
} catch (std::exception const& e) {
- Logger::error("Error loading player file, ignoring! %s", outputException(e, false));
+ Logger::error("Error loading player file, ignoring! {}", outputException(e, false));
m_savedPlayersCache.remove(uuid);
return {};
}
@@ -137,7 +137,7 @@ PlayerPtr PlayerStorage::loadPlayer(Uuid const& uuid) {
void PlayerStorage::deletePlayer(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
- throw PlayerException(strf("No such stored player with uuid '%s'", uuid.hex()));
+ throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
m_savedPlayersCache.remove(uuid);
@@ -156,22 +156,22 @@ void PlayerStorage::deletePlayer(Uuid const& uuid) {
unsigned playerBackupFileCount = configuration->get("playerBackupFileCount").toUInt();
for (unsigned i = 1; i <= playerBackupFileCount; ++i) {
- removeIfExists(strf(".player.bak%d", i));
- removeIfExists(strf(".shipworld.bak%d", i));
+ removeIfExists(strf(".player.bak{}", i));
+ removeIfExists(strf(".shipworld.bak{}", i));
}
}
WorldChunks PlayerStorage::loadShipData(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
- throw PlayerException(strf("No such stored player with uuid '%s'", uuid.hex()));
+ throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
- String filename = File::relativeTo(m_storageDirectory, strf("%s.shipworld", uuid.hex()));
+ String filename = File::relativeTo(m_storageDirectory, strf("{}.shipworld", uuid.hex()));
try {
if (File::exists(filename))
return WorldStorage::getWorldChunksFromFile(filename);
} catch (StarException const& e) {
- Logger::error("Failed to load shipworld file, removing %s : %s", filename, outputException(e, false));
+ Logger::error("Failed to load shipworld file, removing {} : {}", filename, outputException(e, false));
File::remove(filename);
}
@@ -181,12 +181,12 @@ WorldChunks PlayerStorage::loadShipData(Uuid const& uuid) {
void PlayerStorage::applyShipUpdates(Uuid const& uuid, WorldChunks const& updates) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
- throw PlayerException(strf("No such stored player with uuid '%s'", uuid.hex()));
+ throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
if (updates.empty())
return;
- String filename = File::relativeTo(m_storageDirectory, strf("%s.shipworld", uuid.hex()));
+ String filename = File::relativeTo(m_storageDirectory, strf("{}.shipworld", uuid.hex()));
WorldStorage::applyWorldChunksUpdateToFile(filename, updates);
}
@@ -201,9 +201,9 @@ void PlayerStorage::backupCycle(Uuid const& uuid) {
auto configuration = Root::singleton().configuration();
unsigned playerBackupFileCount = configuration->get("playerBackupFileCount").toUInt();
- File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("%s.player", uuid.hex())), playerBackupFileCount, ".bak");
- File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("%s.shipworld", uuid.hex())), playerBackupFileCount, ".bak");
- File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("%s.metadata", uuid.hex())), playerBackupFileCount, ".bak");
+ File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("{}.player", uuid.hex())), playerBackupFileCount, ".bak");
+ File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("{}.shipworld", uuid.hex())), playerBackupFileCount, ".bak");
+ File::backupFileInSequence(File::relativeTo(m_storageDirectory, strf("{}.metadata", uuid.hex())), playerBackupFileCount, ".bak");
}
void PlayerStorage::setMetadata(String key, Json value) {
diff --git a/source/game/StarPlayerTech.cpp b/source/game/StarPlayerTech.cpp
index 604c6a6..133f5f7 100644
--- a/source/game/StarPlayerTech.cpp
+++ b/source/game/StarPlayerTech.cpp
@@ -43,7 +43,7 @@ bool PlayerTech::isEnabled(String const& techModule) const {
void PlayerTech::enable(String const& techModule) {
if (!m_availableTechs.contains(techModule))
- throw PlayerTechException::format("Enabling tech module '%s' when not available", techModule);
+ throw PlayerTechException::format("Enabling tech module '{}' when not available", techModule);
m_enabledTechs.add(techModule);
}
@@ -62,7 +62,7 @@ bool PlayerTech::isEquipped(String const& techModule) const {
void PlayerTech::equip(String const& techModule) {
if (!m_enabledTechs.contains(techModule))
- throw PlayerTechException::format("Equipping tech module '%s' when not enabled", techModule);
+ throw PlayerTechException::format("Equipping tech module '{}' when not enabled", techModule);
auto techDatabase = Root::singleton().techDatabase();
m_equippedTechs[techDatabase->tech(techModule).type] = techModule;
diff --git a/source/game/StarProjectile.cpp b/source/game/StarProjectile.cpp
index 698428b..ad92883 100644
--- a/source/game/StarProjectile.cpp
+++ b/source/game/StarProjectile.cpp
@@ -530,7 +530,7 @@ void Projectile::setFrame(int frame) {
}
String Projectile::drawableFrame() {
- return strf("%s:%d%s", m_config->image, m_frame, m_imageDirectives);
+ return strf("{}:{}{}", m_config->image, m_frame, m_imageDirectives);
}
bool Projectile::ephemeral() const {
@@ -580,7 +580,7 @@ void Projectile::processAction(Json const& action) {
List<Vec2I> openSpaces = world()->findEmptyTiles(m_lastNonCollidingTile, parameters.getInt("radius", 2), totalDrops);
if (openSpaces.size() < totalDrops)
- Logger::debug("Couldn't find a place for all the tile drops. %d drops requested, %d spaces found.", totalDrops, openSpaces.size());
+ Logger::debug("Couldn't find a place for all the tile drops. {} drops requested, {} spaces found.", totalDrops, openSpaces.size());
bool allowEntityOverlap = parameters.getBool("allowEntityOverlap", true);
@@ -842,7 +842,7 @@ void Projectile::processAction(Json const& action) {
processAction(Root::singleton().assets()->json(parameters.getString("file")));
} else {
- throw StarException(strf("Unknown projectile reap command %s", command));
+ throw StarException(strf("Unknown projectile reap command {}", command));
}
}
diff --git a/source/game/StarProjectileDatabase.cpp b/source/game/StarProjectileDatabase.cpp
index 723ae27..2bcd0a7 100644
--- a/source/game/StarProjectileDatabase.cpp
+++ b/source/game/StarProjectileDatabase.cpp
@@ -15,11 +15,11 @@ ProjectileDatabase::ProjectileDatabase() {
try {
auto projectileConfig = readConfig(file);
if (m_configs.contains(projectileConfig->typeName))
- Logger::error("Duplicate projectile asset typeName %s. configfile %s", projectileConfig->typeName, file);
+ Logger::error("Duplicate projectile asset typeName {}. configfile {}", projectileConfig->typeName, file);
else
m_configs[projectileConfig->typeName] = projectileConfig;
} catch (std::exception const& e) {
- Logger::error("Could not read projectile '%s', error: %s", file, outputException(e, false));
+ Logger::error("Could not read projectile '{}', error: {}", file, outputException(e, false));
}
}
}
@@ -34,26 +34,26 @@ bool ProjectileDatabase::isProjectile(String const& projectileName) const {
Json ProjectileDatabase::projectileConfig(String const& type) const {
if (!m_configs.contains(type))
- throw ProjectileDatabaseException(strf("Unknown projectile with typeName %s.", type));
+ throw ProjectileDatabaseException(strf("Unknown projectile with typeName {}.", type));
return m_configs.get(type)->config;
}
ProjectilePtr ProjectileDatabase::createProjectile(String const& type, Json const& parameters) const {
if (!m_configs.contains(type))
- throw ProjectileDatabaseException(strf("Unknown projectile with typeName %s.", type));
+ throw ProjectileDatabaseException(strf("Unknown projectile with typeName {}.", type));
return make_shared<Projectile>(m_configs.get(type), parameters);
}
String ProjectileDatabase::damageKindImage(String const& type) const {
if (!m_configs.contains(type))
- throw ProjectileDatabaseException(strf("Unknown projectile with typeName %s.", type));
+ throw ProjectileDatabaseException(strf("Unknown projectile with typeName {}.", type));
auto& config = m_configs.get(type);
return config->damageKindImage;
}
float ProjectileDatabase::gravityMultiplier(String const& type) const {
if (!m_configs.contains(type))
- throw ProjectileDatabaseException(strf("Unknown projectile with typeName %s.", type));
+ throw ProjectileDatabaseException(strf("Unknown projectile with typeName {}.", type));
auto& config = m_configs.get(type);
return config->movementSettings.getFloat("gravityMultiplier", 1);
}
@@ -81,7 +81,7 @@ ProjectileConfigPtr ProjectileDatabase::readConfig(String const& path) {
auto physicsType = config.getString("physics", "default");
JsonObject movementSettings = config.getObject("movementSettings", JsonObject());
projectileConfig->movementSettings =
- jsonMerge(assets->json(strf("/projectiles/physics.config:%s", physicsType)), movementSettings);
+ jsonMerge(assets->json(strf("/projectiles/physics.config:{}", physicsType)), movementSettings);
projectileConfig->initialSpeed = config.getFloat("speed", 50);
projectileConfig->acceleration = config.getFloat("acceleration", 0);
diff --git a/source/game/StarQuestDescriptor.cpp b/source/game/StarQuestDescriptor.cpp
index 7ea986a..3709ef3 100644
--- a/source/game/StarQuestDescriptor.cpp
+++ b/source/game/StarQuestDescriptor.cpp
@@ -81,7 +81,7 @@ QuestParamDetail questParamDetailFromJson(Json const& json) {
return {};
} else {
- throw StarException::format("Invalid QuestParam type %s", type);
+ throw StarException::format("Invalid QuestParam type {}", type);
}
}
@@ -284,7 +284,7 @@ String questParamText(QuestParam const& parameter) {
} else if (parameter.detail.is<QuestItemList>()) {
QuestItemList itemList = parameter.detail.get<QuestItemList>();
StringList itemStrings = itemList.transformed([&itemDatabase](ItemDescriptor const& itemDesc) -> String {
- return strf("%s %s", itemDesc.count(), itemDatabase->item(itemDesc)->friendlyName());
+ return strf("{} {}", itemDesc.count(), itemDatabase->item(itemDesc)->friendlyName());
});
return itemStrings.join(", ");
diff --git a/source/game/StarQuestManager.cpp b/source/game/StarQuestManager.cpp
index dbc5f4e..9294522 100644
--- a/source/game/StarQuestManager.cpp
+++ b/source/game/StarQuestManager.cpp
@@ -390,7 +390,7 @@ List<QuestPtr> QuestManager::serverQuests() const {
void QuestManager::startInitialQuests() {
auto startingQuests =
- Root::singleton().assets()->json(strf("/quests/quests.config:initialquests.%s", m_player->species())).toArray();
+ Root::singleton().assets()->json(strf("/quests/quests.config:initialquests.{}", m_player->species())).toArray();
for (auto const& questArcJson : startingQuests) {
QuestArcDescriptor quest = QuestArcDescriptor::fromJson(questArcJson);
if (canStart(quest))
diff --git a/source/game/StarQuestTemplateDatabase.cpp b/source/game/StarQuestTemplateDatabase.cpp
index 7b3e3ca..0e2b8a0 100644
--- a/source/game/StarQuestTemplateDatabase.cpp
+++ b/source/game/StarQuestTemplateDatabase.cpp
@@ -65,7 +65,7 @@ QuestTemplateDatabase::QuestTemplateDatabase() {
for (auto qt : files) {
auto questTemplate = make_shared<QuestTemplate>(assets->json(qt));
if (!m_templates.insert(questTemplate->templateId, questTemplate).second)
- throw StarException(strf("Duplicate quest template '%s'", questTemplate->templateId));
+ throw StarException(strf("Duplicate quest template '{}'", questTemplate->templateId));
}
}
@@ -75,7 +75,7 @@ List<String> QuestTemplateDatabase::allQuestTemplateIds() const {
QuestTemplatePtr QuestTemplateDatabase::questTemplate(String const& templateId) const {
if (!m_templates.contains(templateId)) {
- Logger::error("No quest template found for id '%s'", templateId);
+ Logger::error("No quest template found for id '{}'", templateId);
return {};
}
return m_templates.get(templateId);
diff --git a/source/game/StarQuests.cpp b/source/game/StarQuests.cpp
index f8e77bd..8b320b9 100644
--- a/source/game/StarQuests.cpp
+++ b/source/game/StarQuests.cpp
@@ -73,7 +73,7 @@ Quest::Quest(QuestArcDescriptor const& questArc, size_t arcPos, Player* player)
addReward(rewardParam.detail.get<QuestItem>().descriptor());
} else {
if (!rewardParam.detail.is<QuestItemList>())
- throw StarException::format("Quest parameter %s cannot be used as a reward parameter", rewardParamName);
+ throw StarException::format("Quest parameter {} cannot be used as a reward parameter", rewardParamName);
for (auto item : rewardParam.detail.get<QuestItemList>())
addReward(item);
}
diff --git a/source/game/StarRadioMessageDatabase.cpp b/source/game/StarRadioMessageDatabase.cpp
index 8aa5dd5..2a22fe1 100644
--- a/source/game/StarRadioMessageDatabase.cpp
+++ b/source/game/StarRadioMessageDatabase.cpp
@@ -19,12 +19,12 @@ RadioMessageDatabase::RadioMessageDatabase() {
Json messages = assets->json(file);
for (auto pair : messages.iterateObject()) {
if (m_radioMessages.contains(pair.first))
- throw RadioMessageDatabaseException(strf("Duplicate radiomessage %s in file %s", pair.first, file));
+ throw RadioMessageDatabaseException(strf("Duplicate radiomessage {} in file {}", pair.first, file));
m_radioMessages[pair.first] = createRadioMessage(pair.second, pair.first);
}
} catch (std::exception const& e) {
- throw RadioMessageDatabaseException(strf("Error loading radiomessages file %s", file), e);
+ throw RadioMessageDatabaseException(strf("Error loading radiomessages file {}", file), e);
}
}
}
@@ -32,7 +32,7 @@ RadioMessageDatabase::RadioMessageDatabase() {
RadioMessage RadioMessageDatabase::radioMessage(String const& messageName) const {
if (auto message = m_radioMessages.maybe(messageName))
return message.take();
- throw RadioMessageDatabaseException(strf("Unknown radio message %s", messageName));
+ throw RadioMessageDatabaseException(strf("Unknown radio message {}", messageName));
}
RadioMessage RadioMessageDatabase::createRadioMessage(Json const& config, Maybe<String> const& messageId) const {
@@ -65,7 +65,7 @@ RadioMessage RadioMessageDatabase::createRadioMessage(Json const& config, Maybe<
if (message.portraitFrames <= 0)
throw RadioMessageDatabaseException(
- strf("Invalid portraitFrames %s in radio message config!", message.portraitFrames));
+ strf("Invalid portraitFrames {} in radio message config!", message.portraitFrames));
return message;
} else {
diff --git a/source/game/StarRoot.cpp b/source/game/StarRoot.cpp
index 8758447..064ce9d 100644
--- a/source/game/StarRoot.cpp
+++ b/source/game/StarRoot.cpp
@@ -356,7 +356,7 @@ AssetsConstPtr Root::assets() {
assetDirectories.appendAll(m_modDirectories);
auto assets = make_shared<Assets>(m_settings.assetsSettings, scanForAssetSources(assetDirectories));
- Logger::info("Assets digest is %s", hexEncode(assets->digest()));
+ Logger::info("Assets digest is {}", hexEncode(assets->digest()));
return assets;
});
}
@@ -380,7 +380,7 @@ ConfigurationPtr Root::configuration() {
currentConfig = config;
} catch (std::exception const& e) {
- Logger::warn("Root: Failed to load user configuration file %s, resetting user config: %s", *m_runtimeConfigFile, outputException(e, false));
+ Logger::warn("Root: Failed to load user configuration file {}, resetting user config: {}", *m_runtimeConfigFile, outputException(e, false));
currentConfig = m_settings.defaultConfiguration;
File::rename(*m_runtimeConfigFile, *m_runtimeConfigFile + ".old");
}
@@ -562,23 +562,23 @@ StringList Root::scanForAssetSources(StringList const& directories) {
for (auto const& directory : directories) {
if (!File::isDirectory(directory)) {
- Logger::info("Root: Skipping asset directory '%s', directory not found", directory);
+ Logger::info("Root: Skipping asset directory '{}', directory not found", directory);
continue;
}
- Logger::info("Root: Scanning for asset sources in directory '%s'", directory);
+ Logger::info("Root: Scanning for asset sources in directory '{}'", directory);
for (auto entry : File::dirList(directory, true).sorted()) {
AssetSourcePtr source;
auto fileName = File::relativeTo(directory, entry.first);
if (entry.first.beginsWith(".") || entry.first.beginsWith("_"))
- Logger::info("Root: Skipping hidden '%s' in asset directory", entry.first);
+ Logger::info("Root: Skipping hidden '{}' in asset directory", entry.first);
else if (entry.second)
source = make_shared<DirectoryAssetSource>(fileName);
else if (entry.first.endsWith(".pak"))
source = make_shared<PackedAssetSource>(fileName);
else
- Logger::warn("Root: Unrecognized file in asset directory '%s', skipping", entry.first);
+ Logger::warn("Root: Unrecognized file in asset directory '{}', skipping", entry.first);
if (!source)
continue;
@@ -595,11 +595,11 @@ StringList Root::scanForAssetSources(StringList const& directories) {
if (assetSource->name) {
if (auto oldAssetSource = namedSources.value(*assetSource->name)) {
if (oldAssetSource->priority <= assetSource->priority) {
- Logger::warn("Root: Overriding duplicate asset source '%s' named '%s' with higher or equal priority source '%s",
+ Logger::warn("Root: Overriding duplicate asset source '{}' named '{}' with higher or equal priority source '{}",
oldAssetSource->path, *assetSource->name, assetSource->path);
*oldAssetSource = *assetSource;
} else {
- Logger::warn("Root: Skipping duplicate asset source '%s' named '%s', previous source '%s' has higher priority",
+ Logger::warn("Root: Skipping duplicate asset source '{}' named '{}', previous source '{}' has higher priority",
assetSource->path, *assetSource->name, oldAssetSource->priority);
}
} else {
@@ -644,7 +644,7 @@ StringList Root::scanForAssetSources(StringList const& directories) {
if (auto requirement = namedSources.ptr(requirementName))
dependencySortVisit(*requirement);
else
- throw StarException(strf("Asset source '%s' is missing dependency '%s'", *source->name, requirementName));
+ throw StarException(strf("Asset source '{}' is missing dependency '{}'", *source->name, requirementName));
}
workingSet.remove(source);
@@ -658,9 +658,9 @@ StringList Root::scanForAssetSources(StringList const& directories) {
StringList sourcePaths;
for (auto const& source : dependencySortedSources) {
if (source->name)
- Logger::info("Root: Detected asset source named '%s' at '%s'", *source->name, source->path);
+ Logger::info("Root: Detected asset source named '{}' at '{}'", *source->name, source->path);
else
- Logger::info("Root: Detected unnamed asset source at '%s'", source->path);
+ Logger::info("Root: Detected unnamed asset source at '{}'", source->path);
sourcePaths.append(source->path);
}
@@ -672,7 +672,7 @@ void Root::writeConfig() {
auto currentConfig = m_configuration->currentConfiguration();
if (m_lastRuntimeConfig != currentConfig) {
if (m_runtimeConfigFile) {
- Logger::info("Root: Writing runtime configuration to '%s'", *m_runtimeConfigFile);
+ Logger::info("Root: Writing runtime configuration to '{}'", *m_runtimeConfigFile);
File::overwriteFileWithRename(currentConfig.printJson(2, true), *m_runtimeConfigFile);
}
m_lastRuntimeConfig = currentConfig;
@@ -693,7 +693,7 @@ shared_ptr<T> Root::loadMemberFunction(shared_ptr<T>& ptr, Mutex& mutex, char co
if (!ptr) {
auto startSeconds = Time::monotonicTime();
ptr = loadFunction();
- Logger::info("Root: Loaded %s in %s seconds", name, Time::monotonicTime() - startSeconds);
+ Logger::info("Root: Loaded {} in {} seconds", name, Time::monotonicTime() - startSeconds);
}
return ptr;
}
diff --git a/source/game/StarRootLoader.cpp b/source/game/StarRootLoader.cpp
index 0bba5e5..5c90eb7 100644
--- a/source/game/StarRootLoader.cpp
+++ b/source/game/StarRootLoader.cpp
@@ -96,15 +96,15 @@ RootLoader::RootLoader(Defaults defaults) {
addParameter("bootconfig", "bootconfig", Optional,
strf("Boot time configuration file, defaults to sbinit.config"));
addParameter("logfile", "logfile", Optional,
- strf("Log to the given logfile relative to the root directory, defaults to %s",
+ strf("Log to the given logfile relative to the root directory, defaults to {}",
defaults.logFile ? *defaults.logFile : "no log file"));
addParameter("loglevel", "level", Optional,
- strf("Sets the logging level (debug|info|warn|error), defaults to %s",
+ strf("Sets the logging level (debug|info|warn|error), defaults to {}",
LogLevelNames.getRight(defaults.logLevel)));
- addSwitch("quiet", strf("Do not log to stdout, defaults to %s", defaults.quiet));
- addSwitch("verbose", strf("Log to stdout, defaults to %s", !defaults.quiet));
+ addSwitch("quiet", strf("Do not log to stdout, defaults to {}", defaults.quiet));
+ addSwitch("verbose", strf("Log to stdout, defaults to {}", !defaults.quiet));
addSwitch("runtimeconfig",
- strf("Sets the path to the runtime configuration storage file relative to root directory, defauts to %s",
+ strf("Sets the path to the runtime configuration storage file relative to root directory, defauts to {}",
defaults.runtimeConfigFile ? *defaults.runtimeConfigFile : "no storage file"));
m_defaults = move(defaults);
}
diff --git a/source/game/StarServerClientContext.cpp b/source/game/StarServerClientContext.cpp
index c3546a1..ff5b57a 100644
--- a/source/game/StarServerClientContext.cpp
+++ b/source/game/StarServerClientContext.cpp
@@ -91,7 +91,7 @@ bool ServerClientContext::canBecomeAdmin() const {
String ServerClientContext::descriptiveName() const {
RecursiveMutexLocker locker(m_mutex);
String hostName = m_remoteAddress ? toString(*m_remoteAddress) : "local";
- return strf("'%s' <%s> (%s)", m_playerName, m_clientId, hostName);
+ return strf("'{}' <{}> ({})", m_playerName, m_clientId, hostName);
}
void ServerClientContext::registerRpcHandlers(JsonRpcHandlers const& rpcHandlers) {
diff --git a/source/game/StarSongbook.cpp b/source/game/StarSongbook.cpp
index 2e00c27..98c9ec7 100644
--- a/source/game/StarSongbook.cpp
+++ b/source/game/StarSongbook.cpp
@@ -38,7 +38,7 @@ Songbook::~Songbook() {
Songbook::NoteMapping& Songbook::noteMapping(String const& instrument, String const& species, int note) {
if (!m_noteMapping.contains(instrument)) {
Map<int, NoteMapping> notemap;
- auto tuning = Root::singleton().assets()->json(strf("/sfx/instruments/%s/tuning.config", instrument));
+ auto tuning = Root::singleton().assets()->json(strf("/sfx/instruments/{}/tuning.config", instrument));
for (auto e : tuning.get("mapping").iterateObject()) {
int keyNumber = lexicalCast<int>(e.first);
NoteMapping nm;
@@ -95,7 +95,7 @@ void Songbook::update(EntityMode mode, World* world) {
m_stopped = false;
m_track.appendAll(parseABC(m_song.getString("abc")));
} catch (StarException const& e) {
- Logger::error("Failed to handle abc: %s", outputException(e, true));
+ Logger::error("Failed to handle abc: {}", outputException(e, true));
m_stopped = true;
}
}
@@ -216,7 +216,7 @@ List<Songbook::Note> Songbook::parseABC(String const& abc) {
auto keys = Root::singleton().assets()->json("/songbook.config:keys");
while (true) {
if (!keys.contains(key)) {
- Logger::info("Failed to find key %s, falling back to C", key);
+ Logger::info("Failed to find key {}, falling back to C", key);
key = "c";
}
auto signature = keys.get(key);
@@ -503,7 +503,7 @@ List<Songbook::Note> Songbook::parseABC(String const& abc) {
break;
}
default:
- throw StarException(strf("Unrecognized note %s", (char)head));
+ throw StarException(strf("Unrecognized note {}", (char)head));
}
if (note != 0) {
bool accidentalActive = accidentalSpecified;
@@ -556,7 +556,7 @@ List<Songbook::Note> Songbook::parseABC(String const& abc) {
break;
}
default:
- throw StarException(strf("Unrecognized note %s", (char)head));
+ throw StarException(strf("Unrecognized note {}", (char)head));
}
}
diff --git a/source/game/StarSpawnTypeDatabase.cpp b/source/game/StarSpawnTypeDatabase.cpp
index e12694d..2affb5a 100644
--- a/source/game/StarSpawnTypeDatabase.cpp
+++ b/source/game/StarSpawnTypeDatabase.cpp
@@ -124,7 +124,7 @@ SpawnTypeDatabase::SpawnTypeDatabase() {
auto spawnType = spawnTypeFromJson(entry);
if (m_spawnTypes.contains(spawnType.typeName))
- throw SpawnTypeDatabaseException::format("Duplicate spawnType named '%s' in config file '%s'", spawnType.typeName, file);
+ throw SpawnTypeDatabaseException::format("Duplicate spawnType named '{}' in config file '{}'", spawnType.typeName, file);
if (!entry.contains("seedMix"))
spawnType.seedMix = ++seedMix;
@@ -132,7 +132,7 @@ SpawnTypeDatabase::SpawnTypeDatabase() {
m_spawnTypes[spawnType.typeName] = spawnType;
}
} catch (std::exception const& e) {
- throw SpawnTypeDatabaseException(strf("Error reading spawnType config file %s", file), e);
+ throw SpawnTypeDatabaseException(strf("Error reading spawnType config file {}", file), e);
}
}
}
@@ -140,7 +140,7 @@ SpawnTypeDatabase::SpawnTypeDatabase() {
SpawnType SpawnTypeDatabase::spawnType(String const& typeName) const {
if (auto spawnType = m_spawnTypes.maybe(typeName))
return spawnType.take();
- throw SpawnTypeDatabaseException::format("No such spawnType '%s'", typeName);
+ throw SpawnTypeDatabaseException::format("No such spawnType '{}'", typeName);
}
}
diff --git a/source/game/StarSpawner.cpp b/source/game/StarSpawner.cpp
index 9fe2d00..4c54ed4 100644
--- a/source/game/StarSpawner.cpp
+++ b/source/game/StarSpawner.cpp
@@ -338,12 +338,12 @@ void Spawner::debugShowSpawnCells() {
StringList areaList;
for (auto area : debugInfo.second.spawnParameters.areas)
areaList.append(SpawnParameters::AreaNames.getRight(area).slice(0, 3));
- SpatialLogger::logText("world", strf("Areas: %s", areaList.join(", ")), spawnRegion.min() + Vec2F(0.5, 2.5), {255, 255, 255, 255});
- SpatialLogger::logText("world", strf("Region: %s", SpawnParameters::RegionNames.getRight(debugInfo.second.spawnParameters.region)), spawnRegion.min() + Vec2F(0.5, 1.5), {255, 255, 255, 255});
- SpatialLogger::logText("world", strf("Time: %s", SpawnParameters::TimeNames.getRight(debugInfo.second.spawnParameters.time)), spawnRegion.min() + Vec2F(0.5, 0.5), {255, 255, 255, 255});
+ SpatialLogger::logText("world", strf("Areas: {}", areaList.join(", ")), spawnRegion.min() + Vec2F(0.5, 2.5), {255, 255, 255, 255});
+ SpatialLogger::logText("world", strf("Region: {}", SpawnParameters::RegionNames.getRight(debugInfo.second.spawnParameters.region)), spawnRegion.min() + Vec2F(0.5, 1.5), {255, 255, 255, 255});
+ SpatialLogger::logText("world", strf("Time: {}", SpawnParameters::TimeNames.getRight(debugInfo.second.spawnParameters.time)), spawnRegion.min() + Vec2F(0.5, 0.5), {255, 255, 255, 255});
if (debugInfo.second.spawnAttempts > 0)
- SpatialLogger::logText("world", strf("Spawns: %s / %s", debugInfo.second.spawns, debugInfo.second.spawnAttempts), spawnRegion.min() + Vec2F(0.5, 3.5), (debugInfo.second.spawnAttempts > debugInfo.second.spawns) ? Color::Red.toRgba() : Color::Green.toRgba());
+ SpatialLogger::logText("world", strf("Spawns: {} / {}", debugInfo.second.spawns, debugInfo.second.spawnAttempts), spawnRegion.min() + Vec2F(0.5, 3.5), (debugInfo.second.spawnAttempts > debugInfo.second.spawns) ? Color::Red.toRgba() : Color::Green.toRgba());
}
}
}
diff --git a/source/game/StarSpeciesDatabase.cpp b/source/game/StarSpeciesDatabase.cpp
index 1e40942..fe0fdef 100644
--- a/source/game/StarSpeciesDatabase.cpp
+++ b/source/game/StarSpeciesDatabase.cpp
@@ -32,7 +32,7 @@ SpeciesDatabase::SpeciesDatabase() {
for (auto file : files) {
auto speciesDefinition = make_shared<SpeciesDefinition>(assets->json(file));
if (m_species.contains(speciesDefinition->kind()))
- throw StarException(strf("Duplicate species asset with kind %s. configfile %s", speciesDefinition->kind(), file));
+ throw StarException(strf("Duplicate species asset with kind {}. configfile {}", speciesDefinition->kind(), file));
auto k = speciesDefinition->kind().toLower();
m_species[k] = speciesDefinition;
}
@@ -41,7 +41,7 @@ SpeciesDatabase::SpeciesDatabase() {
SpeciesDefinitionPtr SpeciesDatabase::species(String const& kind) const {
auto k = kind.toLower();
if (!m_species.contains(k))
- throw StarException(strf("Unknown species kind '%s'.", kind));
+ throw StarException(strf("Unknown species kind '{}'.", kind));
return m_species.get(k);
}
diff --git a/source/game/StarStagehandDatabase.cpp b/source/game/StarStagehandDatabase.cpp
index c3e71b8..1bf44e0 100644
--- a/source/game/StarStagehandDatabase.cpp
+++ b/source/game/StarStagehandDatabase.cpp
@@ -17,12 +17,12 @@ StagehandDatabase::StagehandDatabase() {
String typeName = config.getString("type");
if (m_stagehandTypes.contains(typeName))
- throw StagehandDatabaseException(strf("Repeat stagehand type name '%s'", typeName));
+ throw StagehandDatabaseException(strf("Repeat stagehand type name '{}'", typeName));
m_stagehandTypes[typeName] = config;
} catch (StarException const& e) {
- throw StagehandDatabaseException(strf("Error loading stagehand type '%s'", file), e);
+ throw StagehandDatabaseException(strf("Error loading stagehand type '{}'", file), e);
}
}
}
diff --git a/source/game/StarStatSet.cpp b/source/game/StarStatSet.cpp
index 4d9c750..aa6513e 100644
--- a/source/game/StarStatSet.cpp
+++ b/source/game/StarStatSet.cpp
@@ -5,13 +5,13 @@ namespace Star {
void StatSet::addStat(String statName, float baseValue) {
if (!m_baseStats.insert(move(statName), baseValue).second)
- throw StatusException::format("Added duplicate stat named '%s' in StatSet", statName);
+ throw StatusException::format("Added duplicate stat named '{}' in StatSet", statName);
update(0.0f);
}
void StatSet::removeStat(String const& statName) {
if (!m_baseStats.remove(statName))
- throw StatusException::format("No such base stat '%s' in StatSet", statName);
+ throw StatusException::format("No such base stat '{}' in StatSet", statName);
update(0.0f);
}
@@ -26,7 +26,7 @@ bool StatSet::isBaseStat(String const& statName) const {
float StatSet::statBaseValue(String const& statName) const {
if (auto s = m_baseStats.ptr(statName))
return *s;
- throw StatusException::format("No such base stat '%s' in StatSet", statName);
+ throw StatusException::format("No such base stat '{}' in StatSet", statName);
}
void StatSet::setStatBaseValue(String const& statName, float value) {
@@ -36,7 +36,7 @@ void StatSet::setStatBaseValue(String const& statName, float value) {
update(0.0f);
}
} else {
- throw StatusException::format("No such base stat '%s' in StatSet", statName);
+ throw StatusException::format("No such base stat '{}' in StatSet", statName);
}
}
@@ -120,13 +120,13 @@ float StatSet::statEffectiveValue(String const& statName) const {
void StatSet::addResource(String resourceName, MVariant<String, float> max, MVariant<String, float> delta) {
auto pair = m_resources.insert({move(resourceName), Resource{move(max), move(delta), false, 0.0f, {}}});
if (!pair.second)
- throw StatusException::format("Added duplicate resource named '%s' in StatSet", resourceName);
+ throw StatusException::format("Added duplicate resource named '{}' in StatSet", resourceName);
update(0.0f);
}
void StatSet::removeResource(String const& resourceName) {
if (!m_resources.remove(resourceName))
- throw StatusException::format("No such resource named '%s' in StatSet", resourceName);
+ throw StatusException::format("No such resource named '{}' in StatSet", resourceName);
}
StringList StatSet::resourceNames() const {
@@ -199,7 +199,7 @@ Maybe<float> StatSet::resourcePercentage(String const& resourceName) const {
float StatSet::setResourcePercentage(String const& resourceName, float resourcePercentage) {
auto& resource = getResource(resourceName);
if (!resource.maxValue)
- throw StatusException::format("setResourcePersentage called on resource '%s' which has no maximum", resourceName);
+ throw StatusException::format("setResourcePersentage called on resource '{}' which has no maximum", resourceName);
return resource.setValue(resourcePercentage * *resource.maxValue);
}
@@ -207,7 +207,7 @@ float StatSet::modifyResourcePercentage(String const& resourceName, float resour
auto& resource = getResource(resourceName);
if (!resource.maxValue)
throw StatusException::format(
- "modifyResourcePercentage called on resource '%s' which has no maximum", resourceName);
+ "modifyResourcePercentage called on resource '{}' which has no maximum", resourceName);
return resource.setValue(resource.value + resourcePercentage * *resource.maxValue);
}
@@ -301,18 +301,18 @@ float StatSet::Resource::setValue(float v) {
StatSet::Resource const& StatSet::getResource(String const& resourceName) const {
if (auto r = m_resources.ptr(resourceName))
return *r;
- throw StatusException::format("No such resource '%s' in StatSet", resourceName);
+ throw StatusException::format("No such resource '{}' in StatSet", resourceName);
}
StatSet::Resource& StatSet::getResource(String const& resourceName) {
if (auto r = m_resources.ptr(resourceName))
return *r;
- throw StatusException::format("No such resource '%s' in StatSet", resourceName);
+ throw StatusException::format("No such resource '{}' in StatSet", resourceName);
}
bool StatSet::consumeResourceValue(String const& resourceName, float amount, bool allowOverConsume) {
if (amount < 0.0f)
- throw StatusException::format("StatSet, consumeResource called with negative amount '%s' %s", resourceName, amount);
+ throw StatusException::format("StatSet, consumeResource called with negative amount '{}' {}", resourceName, amount);
if (auto r = m_resources.ptr(resourceName)) {
if (r->locked)
diff --git a/source/game/StarStatistics.cpp b/source/game/StarStatistics.cpp
index f4a1595..6582663 100644
--- a/source/game/StarStatistics.cpp
+++ b/source/game/StarStatistics.cpp
@@ -68,7 +68,7 @@ bool Statistics::reset() {
void Statistics::update() {
if (m_service) {
if (auto error = m_service->error()) {
- Logger::error("Statistics platform service error: %s", *error);
+ Logger::error("Statistics platform service error: {}", *error);
// Service failed. Continue with local stats and achievements only.
m_service = {};
m_initialized = true;
@@ -115,7 +115,7 @@ Json Statistics::Stat::toJson() const {
void Statistics::processEvent(String const& name, Json const& fields) {
if (m_service)
m_service->reportEvent(name, fields);
- Logger::debug("Event %s %s", name, fields);
+ Logger::debug("Event {} {}", name, fields);
auto statisticsDatabase = Root::singleton().statisticsDatabase();
if (auto const& event = statisticsDatabase->event(name)) {
@@ -124,7 +124,7 @@ void Statistics::processEvent(String const& name, Json const& fields) {
}
void Statistics::setStat(String const& name, String const& type, Json const& value) {
- Logger::debug("Stat %s (%s) : %s", name, type, value);
+ Logger::debug("Stat {} ({}) : {}", name, type, value);
m_stats[name] = Stat { type, value };
if (m_service)
m_service->setStat(name, type, value);
@@ -139,7 +139,7 @@ void Statistics::unlockAchievement(String const& name) {
m_achievements.add(name);
if (m_service)
m_service->unlockAchievement(name);
- Logger::debug("Achievement get %s", name);
+ Logger::debug("Achievement get {}", name);
}
bool Statistics::checkAchievement(String const& achievementName) {
@@ -166,7 +166,7 @@ void Statistics::readStatistics() {
}
} catch (std::exception const& e) {
- Logger::warn("Error loading local player statistics file, resetting: %s", outputException(e, false));
+ Logger::warn("Error loading local player statistics file, resetting: {}", outputException(e, false));
}
}
diff --git a/source/game/StarStatisticsDatabase.cpp b/source/game/StarStatisticsDatabase.cpp
index 7a21ef2..d3b993e 100644
--- a/source/game/StarStatisticsDatabase.cpp
+++ b/source/game/StarStatisticsDatabase.cpp
@@ -15,11 +15,11 @@ StatisticsDatabase::StatisticsDatabase() : m_cacheMutex(), m_eventCache() {
try {
String name = assets->json(file).getString("eventName");
if (m_eventPaths.contains(name))
- Logger::error("Event %s defined twice, second time from %s", name, file);
+ Logger::error("Event {} defined twice, second time from {}", name, file);
else
m_eventPaths[name] = file;
} catch (std::exception const& e) {
- Logger::error("Error loading event file %s: %s", file, outputException(e, true));
+ Logger::error("Error loading event file {}: {}", file, outputException(e, true));
}
}
@@ -28,7 +28,7 @@ StatisticsDatabase::StatisticsDatabase() : m_cacheMutex(), m_eventCache() {
Json achievement = assets->json(file);
String name = achievement.getString("name");
if (m_achievementPaths.contains(name))
- Logger::error("Achievement %s defined twice, second time from %s", name, file);
+ Logger::error("Achievement {} defined twice, second time from {}", name, file);
else
m_achievementPaths[name] = file;
@@ -36,7 +36,7 @@ StatisticsDatabase::StatisticsDatabase() : m_cacheMutex(), m_eventCache() {
m_statAchievements[stat.toString()].append(name);
}
} catch (std::exception const& e) {
- Logger::error("Error loading achievement file %s: %s", file, outputException(e, true));
+ Logger::error("Error loading achievement file {}: {}", file, outputException(e, true));
}
}
}
diff --git a/source/game/StarStatusController.cpp b/source/game/StarStatusController.cpp
index 8e26cdc..44f0afc 100644
--- a/source/game/StarStatusController.cpp
+++ b/source/game/StarStatusController.cpp
@@ -702,7 +702,7 @@ void StatusController::addUniqueEffect(
if (m_parentEntity)
initUniqueEffectScript(uniqueEffect);
} else {
- Logger::warn("Unique status effect '%s' not found in status effect database", effect);
+ Logger::warn("Unique status effect '{}' not found in status effect database", effect);
}
}
diff --git a/source/game/StarStatusEffectDatabase.cpp b/source/game/StarStatusEffectDatabase.cpp
index e8255a2..5a060bc 100644
--- a/source/game/StarStatusEffectDatabase.cpp
+++ b/source/game/StarStatusEffectDatabase.cpp
@@ -14,7 +14,7 @@ StatusEffectDatabase::StatusEffectDatabase() {
if (m_uniqueEffects.contains(uniqueEffect.name))
throw StatusEffectDatabaseException::format(
- "Duplicate stat effect named '%s', config file '%s'", uniqueEffect.name, file);
+ "Duplicate stat effect named '{}', config file '{}'", uniqueEffect.name, file);
m_uniqueEffects[uniqueEffect.name] = uniqueEffect;
}
}
@@ -26,7 +26,7 @@ bool StatusEffectDatabase::isUniqueEffect(UniqueStatusEffect const& effect) cons
UniqueStatusEffectConfig StatusEffectDatabase::uniqueEffectConfig(UniqueStatusEffect const& effect) const {
if (auto uniqueEffect = m_uniqueEffects.maybe(effect))
return uniqueEffect.take();
- throw StatusEffectDatabaseException::format("No such unique stat effect '%s'", effect);
+ throw StatusEffectDatabaseException::format("No such unique stat effect '{}'", effect);
}
UniqueStatusEffectConfig StatusEffectDatabase::parseUniqueEffect(Json const& config, String const& path) const {
diff --git a/source/game/StarStoredFunctions.cpp b/source/game/StarStoredFunctions.cpp
index 27a1eef..0db0356 100644
--- a/source/game/StarStoredFunctions.cpp
+++ b/source/game/StarStoredFunctions.cpp
@@ -132,7 +132,7 @@ FunctionDatabase::FunctionDatabase() {
for (auto file : functions) {
for (auto const& functionPair : assets->json(file).iterateObject()) {
if (m_functions.contains(functionPair.first))
- throw StarException(strf("Named Function '%s' defined twice, second time from %s", functionPair.first, file));
+ throw StarException(strf("Named Function '{}' defined twice, second time from {}", functionPair.first, file));
m_functions[functionPair.first] = make_shared<StoredFunction>(parametricFunctionFromConfig(functionPair.second));
}
}
@@ -141,7 +141,7 @@ FunctionDatabase::FunctionDatabase() {
for (auto const& functionPair : assets->json(file).iterateObject()) {
if (m_functions2.contains(functionPair.first))
throw StarException(
- strf("Named 2-ary Function '%s' defined twice, second time from %s", functionPair.first, file));
+ strf("Named 2-ary Function '{}' defined twice, second time from {}", functionPair.first, file));
m_functions2[functionPair.first] = make_shared<StoredFunction2>(multiTable2DFromConfig(functionPair.second));
}
}
@@ -150,7 +150,7 @@ FunctionDatabase::FunctionDatabase() {
for (auto const& tablePair : assets->json(file).iterateObject()) {
if (m_configFunctions.contains(tablePair.first))
throw StarException(
- strf("Named config function '%s' defined twice, second time from %s", tablePair.first, file));
+ strf("Named config function '{}' defined twice, second time from {}", tablePair.first, file));
m_configFunctions[tablePair.first] =
make_shared<StoredConfigFunction>(parametricTableFromConfig(tablePair.second));
}
@@ -211,7 +211,7 @@ ParametricFunction<double, double> FunctionDatabase::parametricFunctionFromConfi
} else if (interpolationModeString.equalsIgnoreCase("Cubic")) {
interpolationMode = InterpolationMode::Cubic;
} else {
- throw StoredFunctionException(strf("Unrecognized InterpolationMode '%s'", interpolationModeString));
+ throw StoredFunctionException(strf("Unrecognized InterpolationMode '{}'", interpolationModeString));
}
BoundMode boundMode;
@@ -222,7 +222,7 @@ ParametricFunction<double, double> FunctionDatabase::parametricFunctionFromConfi
} else if (boundModeString.equalsIgnoreCase("Wrap")) {
boundMode = BoundMode::Wrap;
} else {
- throw StoredFunctionException(strf("Unrecognized BoundMode '%s'", boundModeString));
+ throw StoredFunctionException(strf("Unrecognized BoundMode '{}'", boundModeString));
}
return ParametricFunction<double, double>(points, interpolationMode, boundMode);
@@ -284,7 +284,7 @@ MultiTable2D FunctionDatabase::multiTable2DFromConfig(Json descriptor) {
} else if (interpolationModeString.equalsIgnoreCase("Cubic")) {
interpolationMode = InterpolationMode::Cubic;
} else {
- throw StoredFunctionException(strf("Unrecognized InterpolationMode '%s'", interpolationModeString));
+ throw StoredFunctionException(strf("Unrecognized InterpolationMode '{}'", interpolationModeString));
}
BoundMode boundMode;
@@ -295,7 +295,7 @@ MultiTable2D FunctionDatabase::multiTable2DFromConfig(Json descriptor) {
} else if (boundModeString.equalsIgnoreCase("Wrap")) {
boundMode = BoundMode::Wrap;
} else {
- throw StoredFunctionException(strf("Unrecognized BoundMode '%s'", boundModeString));
+ throw StoredFunctionException(strf("Unrecognized BoundMode '{}'", boundModeString));
}
MultiTable2D table;
diff --git a/source/game/StarSystemWorld.cpp b/source/game/StarSystemWorld.cpp
index e075b78..3708e46 100644
--- a/source/game/StarSystemWorld.cpp
+++ b/source/game/StarSystemWorld.cpp
@@ -272,7 +272,7 @@ SystemObjectConfig SystemWorld::systemObjectConfig(String const& name, Uuid cons
}
Json SystemWorld::systemObjectTypeConfig(String const& name) {
- return Root::singleton().assets()->json(strf("/system_objects.config:%s", name));
+ return Root::singleton().assets()->json(strf("/system_objects.config:{}", name));
}
Maybe<Vec2F> SystemWorld::systemLocationPosition(SystemLocation const& location) const {
diff --git a/source/game/StarSystemWorldServer.cpp b/source/game/StarSystemWorldServer.cpp
index 3cffbc9..1f1dc66 100644
--- a/source/game/StarSystemWorldServer.cpp
+++ b/source/game/StarSystemWorldServer.cpp
@@ -148,10 +148,10 @@ List<InstanceWorldId> SystemWorldServer::activeInstanceWorlds() const {
void SystemWorldServer::removeObject(Uuid objectUuid) {
if (!m_objects.contains(objectUuid))
- throw StarException(strf("Cannot remove object with uuid '%s', object doesn't exist.", objectUuid.hex()));
+ throw StarException(strf("Cannot remove object with uuid '{}', object doesn't exist.", objectUuid.hex()));
if (m_objects[objectUuid]->permanent())
- throw StarException(strf("Cannot remove object with uuid '%s', object is marked permanent", objectUuid.hex()));
+ throw StarException(strf("Cannot remove object with uuid '{}', object is marked permanent", objectUuid.hex()));
// already removing it
if (m_objectDestroyQueue.contains(objectUuid))
@@ -314,7 +314,7 @@ Json SystemWorldServer::diskStore() {
void SystemWorldServer::placeInitialObjects() {
auto config = Root::singleton().assets()->json("/systemworld.config");
- RandomSource rand(staticRandomU64("SystemWorldGeneration", strf("%s", m_location)));
+ RandomSource rand(staticRandomU64("SystemWorldGeneration", strf("{}", m_location)));
WeightedPool<JsonArray> spawnPools = jsonToWeightedPool<JsonArray>(config.getArray("initialObjectPools"));
JsonArray spawn = spawnPools.select(rand);
@@ -429,7 +429,7 @@ SkyParameters SystemWorldServer::locationSkyParameters(SystemLocation const& loc
if (auto visitableParameters = parameters->visitableParameters()) {
if (is<TerrestrialWorldParameters>(visitableParameters)) {
- uint64_t seed = staticRandomU64(strf("%s", m_location));
+ uint64_t seed = staticRandomU64(strf("{}", m_location));
List<CelestialParameters> worlds;
if (auto planet = m_celestialDatabase->parameters(orbitTarget))
worlds.append(*planet);
diff --git a/source/game/StarSystemWorldServerThread.cpp b/source/game/StarSystemWorldServerThread.cpp
index af9c065..dd9b9b8 100644
--- a/source/game/StarSystemWorldServerThread.cpp
+++ b/source/game/StarSystemWorldServerThread.cpp
@@ -5,7 +5,7 @@
namespace Star {
SystemWorldServerThread::SystemWorldServerThread(Vec3I const& location, SystemWorldServerPtr systemWorld, String storageFile)
- : Thread(strf("SystemWorldServer: %s", location)), m_stop(false), m_storageFile(storageFile) {
+ : Thread(strf("SystemWorldServer: {}", location)), m_stop(false), m_storageFile(storageFile) {
m_systemLocation = location;
m_systemWorld = move(systemWorld);
}
@@ -52,7 +52,7 @@ void SystemWorldServerThread::run() {
TickRateApproacher tickApproacher(1.0 / SystemWorldTimestep, 0.5);
while (!m_stop) {
- LogMap::set(strf("system_%s_update_fps", m_systemLocation), tickApproacher.rate());
+ LogMap::set(strf("system_{}_update_fps", m_systemLocation), tickApproacher.rate());
update();
@@ -166,7 +166,7 @@ void SystemWorldServerThread::store() {
Json store = m_systemWorld->diskStore();
locker.unlock();
- Logger::debug("Trigger disk storage for system world %s:%s:%s", m_systemLocation.x(), m_systemLocation.y(), m_systemLocation.z());
+ Logger::debug("Trigger disk storage for system world {}:{}:{}", m_systemLocation.x(), m_systemLocation.y(), m_systemLocation.z());
auto versioningDatabase = Root::singleton().versioningDatabase();
auto versionedStore = versioningDatabase->makeCurrentVersionedJson("System", store);
VersionedJson::writeFile(versionedStore, m_storageFile);
diff --git a/source/game/StarTechController.cpp b/source/game/StarTechController.cpp
index 7ceb54e..8f0c7d7 100644
--- a/source/game/StarTechController.cpp
+++ b/source/game/StarTechController.cpp
@@ -425,7 +425,7 @@ void TechController::setupTechModules(List<tuple<String, JsonObject>> const& mod
moduleAnimator->animator.setPartTag(pair.first, "partImage", pair.second.toString());
module.animatorId = m_techAnimators.addNetElement(moduleAnimator);
} else {
- Logger::warn("Tech module '%s' not found in tech database", get<0>(moduleInit));
+ Logger::warn("Tech module '{}' not found in tech database", get<0>(moduleInit));
}
}
}
diff --git a/source/game/StarTechDatabase.cpp b/source/game/StarTechDatabase.cpp
index ae8defa..a1cce3e 100644
--- a/source/game/StarTechDatabase.cpp
+++ b/source/game/StarTechDatabase.cpp
@@ -19,7 +19,7 @@ TechDatabase::TechDatabase() {
auto tech = parseTech(assets->json(file), file);
if (m_tech.contains(tech.name))
- throw TechDatabaseException::format("Duplicate tech named '%s', config file '%s'", tech.name, file);
+ throw TechDatabaseException::format("Duplicate tech named '{}', config file '{}'", tech.name, file);
m_tech[tech.name] = tech;
}
}
@@ -31,7 +31,7 @@ bool TechDatabase::contains(String const& techName) const {
TechConfig TechDatabase::tech(String const& techName) const {
if (auto p = m_tech.ptr(techName))
return *p;
- throw TechDatabaseException::format("No such tech '%s'", techName);
+ throw TechDatabaseException::format("No such tech '{}'", techName);
}
TechConfig TechDatabase::parseTech(Json const& config, String const& path) const {
@@ -55,7 +55,7 @@ TechConfig TechDatabase::parseTech(Json const& config, String const& path) const
return tech;
} catch (std::exception const& e) {
- throw TechDatabaseException(strf("Error reading tech config %s", path), e);
+ throw TechDatabaseException(strf("Error reading tech config {}", path), e);
}
}
diff --git a/source/game/StarTenantDatabase.cpp b/source/game/StarTenantDatabase.cpp
index 3397bd7..1cfa0c4 100644
--- a/source/game/StarTenantDatabase.cpp
+++ b/source/game/StarTenantDatabase.cpp
@@ -21,11 +21,11 @@ TenantDatabase::TenantDatabase() {
try {
String name = assets->json(file).getString("name");
if (m_paths.contains(name))
- Logger::error("Tenant %s defined twice, second time from %s", name, file);
+ Logger::error("Tenant {} defined twice, second time from {}", name, file);
else
m_paths[name] = file;
} catch (std::exception const& e) {
- Logger::error("Error loading tenant file %s: %s", file, outputException(e, true));
+ Logger::error("Error loading tenant file {}: {}", file, outputException(e, true));
}
}
}
@@ -41,7 +41,7 @@ TenantPtr TenantDatabase::getTenant(String const& name) const {
[this](String const& name) -> TenantPtr {
if (auto path = m_paths.maybe(name))
return readTenant(*path);
- throw TenantException::format("No such tenant named '%s'", name);
+ throw TenantException::format("No such tenant named '{}'", name);
});
}
@@ -96,7 +96,7 @@ TenantPtr TenantDatabase::readTenant(String const& path) {
return make_shared<Tenant>(Tenant{name, priority, colonyTagCriteria, tenants, rent, config});
} catch (std::exception const& e) {
- throw TenantException::format("Error loading tenant '%s': %s", path, outputException(e, false));
+ throw TenantException::format("Error loading tenant '{}': {}", path, outputException(e, false));
}
}
diff --git a/source/game/StarTerrainDatabase.cpp b/source/game/StarTerrainDatabase.cpp
index 22f9365..a2b33fd 100644
--- a/source/game/StarTerrainDatabase.cpp
+++ b/source/game/StarTerrainDatabase.cpp
@@ -65,7 +65,7 @@ TerrainDatabase::TerrainDatabase() {
auto parameters = assets->json(path);
auto name = parameters.getString("name");
if (m_terrainSelectors.contains(name))
- throw TerrainException(strf("Duplicate terrain generator name '%s'", name));
+ throw TerrainException(strf("Duplicate terrain generator name '{}'", name));
m_terrainSelectors[name] = {type, parameters};
}
};
@@ -81,7 +81,7 @@ TerrainDatabase::TerrainDatabase() {
auto name = parameters.getString("name");
auto type = parameters.getString("type");
if (m_terrainSelectors.contains(name))
- throw TerrainException(strf("Duplicate composed terrain generator name '%s'", name));
+ throw TerrainException(strf("Duplicate composed terrain generator name '{}'", name));
m_terrainSelectors[name] = {type, parameters};
}
}
@@ -90,7 +90,7 @@ TerrainDatabase::Config TerrainDatabase::selectorConfig(String const& name) cons
if (auto config = m_terrainSelectors.maybe(name))
return config.take();
else
- throw TerrainException(strf("No such terrain selector '%s'", name));
+ throw TerrainException(strf("No such terrain selector '{}'", name));
}
TerrainSelectorConstPtr TerrainDatabase::createNamedSelector(String const& name, TerrainSelectorParameters const& parameters) const {
@@ -149,7 +149,7 @@ TerrainSelectorConstPtr TerrainDatabase::createSelectorType(String const& type,
else if (type == CacheSelector::Name)
return make_shared<CacheSelector>(config, parameters, this);
else
- throw TerrainException(strf("Unknown terrain selector type '%s'", type));
+ throw TerrainException(strf("Unknown terrain selector type '{}'", type));
}
}
diff --git a/source/game/StarTilesetDatabase.cpp b/source/game/StarTilesetDatabase.cpp
index 5a7a32e..b9827ee 100644
--- a/source/game/StarTilesetDatabase.cpp
+++ b/source/game/StarTilesetDatabase.cpp
@@ -341,7 +341,7 @@ namespace Tiled {
try {
return Json::parseJson(propertyValue);
} catch (JsonParsingException const& e) {
- throw StarException::format("Error parsing Tiled property as Json: %s", outputException(e, false));
+ throw StarException::format("Error parsing Tiled property as Json: {}", outputException(e, false));
}
}
diff --git a/source/game/StarTreasure.cpp b/source/game/StarTreasure.cpp
index 5b7ce84..2efca99 100644
--- a/source/game/StarTreasure.cpp
+++ b/source/game/StarTreasure.cpp
@@ -22,7 +22,7 @@ TreasureDatabase::TreasureDatabase() {
for (auto file : treasurePools) {
for (auto const& pair : assets->json(file).iterateObject()) {
if (m_treasurePools.contains(pair.first))
- throw TreasureException(strf("Duplicate TreasurePool config '%s' from file '%s'", pair.first, file));
+ throw TreasureException(strf("Duplicate TreasurePool config '{}' from file '{}'", pair.first, file));
auto& treasurePool = m_treasurePools[pair.first];
for (auto const& entry : pair.second.iterateArray()) {
@@ -40,18 +40,18 @@ TreasureDatabase::TreasureDatabase() {
else if (entry.contains("item"))
itemPool.fill.append(ItemDescriptor(entry.get("item")));
else
- throw TreasureException(strf("TreasurePool entry '%s' did not specify a valid 'item' or 'pool'", entry));
+ throw TreasureException(strf("TreasurePool entry '{}' did not specify a valid 'item' or 'pool'", entry));
for (auto const& entry : config.getArray("pool", {})) {
if (!entry.contains("weight"))
- throw TreasureException(strf("TreasurePool entry '%s' did not specify a weight", entry));
+ throw TreasureException(strf("TreasurePool entry '{}' did not specify a weight", entry));
if (entry.contains("pool"))
itemPool.pool.add(entry.getFloat("weight"), entry.getString("pool"));
else if (entry.contains("item"))
itemPool.pool.add(entry.getFloat("weight"), ItemDescriptor(entry.get("item")));
else
- throw TreasureException(strf("TreasurePool entry '%s' did not specify a valid 'item' or 'pool'", entry));
+ throw TreasureException(strf("TreasurePool entry '{}' did not specify a valid 'item' or 'pool'", entry));
}
auto poolRounds = config.get("poolRounds", 1);
@@ -73,7 +73,7 @@ TreasureDatabase::TreasureDatabase() {
for (auto file : treasureChests) {
for (auto const& pair : assets->json(file).iterateObject()) {
if (m_treasureChestSets.contains(pair.first))
- throw TreasureException(strf("Duplicate TreasureChestSet config '%s' from file '%s'", pair.first, file));
+ throw TreasureException(strf("Duplicate TreasureChestSet config '{}' from file '{}'", pair.first, file));
auto& treasureChestSet = m_treasureChestSets[pair.first];
for (auto const& entry : pair.second.iterateArray()) {
@@ -84,7 +84,7 @@ TreasureDatabase::TreasureDatabase() {
treasureChest.minimumLevel = entry.getFloat("minimumLevel", 0);
if (!m_treasurePools.contains(treasureChest.treasurePool))
- throw TreasureException(strf("No such TreasurePool '%s' for TreasureChestSet named '%s' in file '%s'", treasureChest.treasurePool, pair.first, file));
+ throw TreasureException(strf("No such TreasurePool '{}' for TreasureChestSet named '{}' in file '{}'", treasureChest.treasurePool, pair.first, file));
treasureChestSet.append(treasureChest);
}
@@ -122,10 +122,10 @@ List<ItemPtr> TreasureDatabase::createTreasure(String const& treasurePool, float
List<ItemPtr> TreasureDatabase::createTreasure(String const& treasurePool, float level, uint64_t seed, StringSet visitedPools) const {
if (!m_treasurePools.contains(treasurePool))
- throw TreasureException(strf("Unknown treasure pool '%s'", treasurePool));
+ throw TreasureException(strf("Unknown treasure pool '{}'", treasurePool));
if (!visitedPools.add(treasurePool))
- throw TreasureException(strf("Loop detected in treasure pool generation - set '%s' already contains '%s'", visitedPools, treasurePool));
+ throw TreasureException(strf("Loop detected in treasure pool generation - set '{}' already contains '{}'", visitedPools, treasurePool));
auto itemDatabase = Root::singleton().itemDatabase();
@@ -197,7 +197,7 @@ ContainerObjectPtr TreasureDatabase::createTreasureChest(World* world, String co
auto objectDatabase = Root::singleton().objectDatabase();
if (!m_treasureChestSets.contains(treasureChestSet))
- throw StarException(strf("Unknown treasure chest set '%s'", treasureChestSet));
+ throw StarException(strf("Unknown treasure chest set '{}'", treasureChestSet));
auto level = world->threatLevel();
auto boxSet = m_treasureChestSets.get(treasureChestSet);
diff --git a/source/game/StarUniverseClient.cpp b/source/game/StarUniverseClient.cpp
index d67d498..9b26416 100644
--- a/source/game/StarUniverseClient.cpp
+++ b/source/game/StarUniverseClient.cpp
@@ -83,7 +83,7 @@ Maybe<String> UniverseClient::connect(UniverseConnection connection, bool allowA
if (!protocolResponsePacket)
return String("Join failed! Timeout while establishing connection.");
else if (!protocolResponsePacket->allowed)
- return String(strf("Join failed! Server does not support connections with protocol version %s", StarProtocolVersion));
+ return String(strf("Join failed! Server does not support connections with protocol version {}", StarProtocolVersion));
connection.pushSingle(make_shared<ClientConnectPacket>(Root::singleton().assets()->digest(), allowAssetsMismatch, m_mainPlayer->uuid(), m_mainPlayer->name(),
m_mainPlayer->species(), m_playerStorage->loadShipData(m_mainPlayer->uuid()), ShipUpgrades(m_mainPlayer->shipUpgrades()),
@@ -117,10 +117,10 @@ Maybe<String> UniverseClient::connect(UniverseConnection connection, bool allowA
m_celestialDatabase = make_shared<CelestialSlaveDatabase>(move(success->celestialInformation));
m_systemWorldClient = make_shared<SystemWorldClient>(m_universeClock, m_celestialDatabase, m_mainPlayer->universeMap());
- Logger::info("UniverseClient: Joined server as client %s", success->clientId);
+ Logger::info("UniverseClient: Joined server as client {}", success->clientId);
return {};
} else if (auto failure = as<ConnectFailurePacket>(packet)) {
- Logger::error("UniverseClient: Join failed: %s", failure->reason);
+ Logger::error("UniverseClient: Join failed: {}", failure->reason);
return failure->reason;
} else {
Logger::error("UniverseClient: Join failed! No server response received");
@@ -279,12 +279,12 @@ void UniverseClient::update() {
if (auto netStats = m_connection->incomingStats()) {
LogMap::set("client_incoming_bps", netStats->bytesPerSecond);
- LogMap::set("client_worst_incoming", strf("%s:%s", PacketTypeNames.getRight(netStats->worstPacketType), netStats->worstPacketSize));
+ LogMap::set("client_worst_incoming", strf("{}:{}", PacketTypeNames.getRight(netStats->worstPacketType), netStats->worstPacketSize));
}
if (auto netStats = m_connection->outgoingStats()) {
LogMap::set("client_outgoing_bps", netStats->bytesPerSecond);
LogMap::set("client_worst_outgoing",
- strf("%s:%s", PacketTypeNames.getRight(netStats->worstPacketType), netStats->worstPacketSize));
+ strf("{}:{}", PacketTypeNames.getRight(netStats->worstPacketType), netStats->worstPacketSize));
}
}
diff --git a/source/game/StarUniverseConnection.cpp b/source/game/StarUniverseConnection.cpp
index 1de6140..e8230bb 100644
--- a/source/game/StarUniverseConnection.cpp
+++ b/source/game/StarUniverseConnection.cpp
@@ -150,7 +150,7 @@ UniverseConnectionServer::UniverseConnectionServer(PacketReceiveCallback packetR
try {
m_packetReceiver(this, p.first, move(toReceive));
} catch (std::exception const& e) {
- Logger::error("Exception caught handling incoming server packets, disconnecting client '%s' %s", p.first, outputException(e, true));
+ Logger::error("Exception caught handling incoming server packets, disconnecting client '{}' {}", p.first, outputException(e, true));
connectionLocker.lock();
p.second->packetSocket->close();
@@ -162,7 +162,7 @@ UniverseConnectionServer::UniverseConnectionServer(PacketReceiveCallback packetR
Thread::sleep(PacketSocketPollSleep);
}
} catch (std::exception const& e) {
- Logger::error("Exception caught in UniverseConnectionServer::remoteProcessLoop, closing all remote connections: %s", e.what());
+ Logger::error("Exception caught in UniverseConnectionServer::remoteProcessLoop, closing all remote connections: {}", e.what());
connectionsLocker.lock();
for (auto& p : m_connections)
p.second->packetSocket->close();
@@ -193,7 +193,7 @@ bool UniverseConnectionServer::connectionIsOpen(ConnectionId clientId) const {
return conn->packetSocket->isOpen();
}
- throw UniverseConnectionException::format("No such client '%s' in UniverseConnectionServer::connectionIsOpen", clientId);
+ throw UniverseConnectionException::format("No such client '{}' in UniverseConnectionServer::connectionIsOpen", clientId);
}
int64_t UniverseConnectionServer::lastActivityTime(ConnectionId clientId) const {
@@ -202,13 +202,13 @@ int64_t UniverseConnectionServer::lastActivityTime(ConnectionId clientId) const
MutexLocker connectionLocker(conn->mutex);
return conn->lastActivityTime;
}
- throw UniverseConnectionException::format("No such client '%s' in UniverseConnectionServer::lastRemoteActivityTime", clientId);
+ throw UniverseConnectionException::format("No such client '{}' in UniverseConnectionServer::lastRemoteActivityTime", clientId);
}
void UniverseConnectionServer::addConnection(ConnectionId clientId, UniverseConnection uc) {
RecursiveMutexLocker connectionsLocker(m_connectionsMutex);
if (m_connections.contains(clientId))
- throw UniverseConnectionException::format("Client '%s' already exists in UniverseConnectionServer::addConnection", clientId);
+ throw UniverseConnectionException::format("Client '{}' already exists in UniverseConnectionServer::addConnection", clientId);
auto connection = make_shared<Connection>();
connection->packetSocket = move(uc.m_packetSocket);
@@ -221,7 +221,7 @@ void UniverseConnectionServer::addConnection(ConnectionId clientId, UniverseConn
UniverseConnection UniverseConnectionServer::removeConnection(ConnectionId clientId) {
RecursiveMutexLocker connectionsLocker(m_connectionsMutex);
if (!m_connections.contains(clientId))
- throw UniverseConnectionException::format("Client '%s' does not exist in UniverseConnectionServer::removeConnection", clientId);
+ throw UniverseConnectionException::format("Client '{}' does not exist in UniverseConnectionServer::removeConnection", clientId);
auto conn = m_connections.take(clientId);
MutexLocker connectionLocker(conn->mutex);
@@ -252,7 +252,7 @@ void UniverseConnectionServer::sendPackets(ConnectionId clientId, List<PacketPtr
conn->packetSocket->writeData();
}
} else {
- throw UniverseConnectionException::format("No such client '%s' in UniverseConnectionServer::sendPackets", clientId);
+ throw UniverseConnectionException::format("No such client '{}' in UniverseConnectionServer::sendPackets", clientId);
}
}
diff --git a/source/game/StarUniverseServer.cpp b/source/game/StarUniverseServer.cpp
index e2f6215..7742d1e 100644
--- a/source/game/StarUniverseServer.cpp
+++ b/source/game/StarUniverseServer.cpp
@@ -39,7 +39,7 @@ UniverseServer::UniverseServer(String const& storageDir)
if (auto assetsDigestOverride = configuration->get("serverOverrideAssetsDigest").optString()) {
m_assetsDigest = hexDecode(*assetsDigestOverride);
- Logger::info("UniverseServer: Overriding assets digest as '%s'", *assetsDigestOverride);
+ Logger::info("UniverseServer: Overriding assets digest as '{}'", *assetsDigestOverride);
} else {
m_assetsDigest = assets->digest();
}
@@ -449,7 +449,7 @@ bool UniverseServer::updatePlanetType(CelestialCoordinate const& coordinate, Str
}
void UniverseServer::run() {
- Logger::info("UniverseServer: Starting UniverseServer with UUID: %s", m_universeSettings->uuid().hex());
+ Logger::info("UniverseServer: Starting UniverseServer with UUID: {}", m_universeSettings->uuid().hex());
int mainWakeupInterval = Root::singleton().assets()->json("/universe_server.config:mainWakeupInterval").toInt();
@@ -463,18 +463,18 @@ void UniverseServer::run() {
HostAddressWithPort bindAddress(configuration->get("gameServerBind").toString(), configuration->get("gameServerPort").toUInt());
unsigned maxPendingConnections = assets->json("/universe_server.config:maxPendingConnections").toInt();
- Logger::info("UniverseServer: listening for incoming TCP connections on %s", bindAddress);
+ Logger::info("UniverseServer: listening for incoming TCP connections on {}", bindAddress);
tcpServer = make_shared<TcpServer>(bindAddress);
tcpServer->setAcceptCallback([this, maxPendingConnections](TcpSocketPtr socket) {
RecursiveMutexLocker locker(m_mainLock);
if (m_connectionAcceptThreads.size() < maxPendingConnections) {
- Logger::info("UniverseServer: Connection received from: %s", socket->remoteAddress());
+ Logger::info("UniverseServer: Connection received from: {}", socket->remoteAddress());
m_connectionAcceptThreads.append(Thread::invoke("UniverseServer::acceptConnection", [this, socket]() {
acceptConnection(UniverseConnection(TcpPacketSocket::open(socket)), socket->remoteAddress().address());
}));
} else {
- Logger::warn("UniverseServer: maximum pending connections, dropping connection from: %s", socket->remoteAddress().address());
+ Logger::warn("UniverseServer: maximum pending connections, dropping connection from: {}", socket->remoteAddress().address());
}
});
@@ -505,7 +505,7 @@ void UniverseServer::run() {
shutdownInactiveWorlds();
doTriggeredStorage();
} catch (std::exception const& e) {
- Logger::error("UniverseServer: exception caught: %s", outputException(e, true));
+ Logger::error("UniverseServer: exception caught: {}", outputException(e, true));
}
Thread::sleep(mainWakeupInterval);
@@ -531,7 +531,7 @@ void UniverseServer::run() {
m_worlds.clear();
} catch (std::exception const& e) {
- Logger::error("UniverseServer: exception caught cleaning up: %s", outputException(e, true));
+ Logger::error("UniverseServer: exception caught cleaning up: {}", outputException(e, true));
}
}
@@ -700,7 +700,7 @@ void UniverseServer::reapConnections() {
try {
function.finish();
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Exception caught accepting new connection: %s", outputException(e, true));
+ Logger::error("UniverseServer: Exception caught accepting new connection: {}", outputException(e, true));
}
}
return function.isFinished();
@@ -713,11 +713,11 @@ void UniverseServer::reapConnections() {
for (auto clientId : m_clients.keys()) {
auto clientContext = m_clients.value(clientId);
if (!m_connectionServer->connectionIsOpen(clientId)) {
- Logger::info("UniverseServer: Client %s connection lost", clientContext->descriptiveName());
+ Logger::info("UniverseServer: Client {} connection lost", clientContext->descriptiveName());
doDisconnection(clientId, String("Disconnected due to connection lost"));
} else {
if (clientContext->remoteAddress() && startTime - m_connectionServer->lastActivityTime(clientId) > timeout) {
- Logger::info("UniverseServer: Kicking client %s due to inactivity", clientContext->descriptiveName());
+ Logger::info("UniverseServer: Kicking client {} due to inactivity", clientContext->descriptiveName());
doDisconnection(clientId, String("Disconnected due to inactivity"));
}
}
@@ -733,7 +733,7 @@ void UniverseServer::reapConnections() {
return pair.first.isOpen() && startTime - pair.second < timeout;
});
if (previousDeadConnections > m_deadConnections.size())
- Logger::info("UniverseServer: Reaped %s dead connections", previousDeadConnections);
+ Logger::info("UniverseServer: Reaped {} dead connections", previousDeadConnections);
}
void UniverseServer::processPlanetTypeChanges() {
@@ -765,7 +765,7 @@ void UniverseServer::warpPlayers() {
WarpToWorld warpToWorld = resolveWarpAction(warpAction, clientId, deploy);
if (auto maybeToWorld = triggerWorldCreation(warpToWorld.world)) {
- Logger::info("UniverseServer: Warping player %s to %s", clientId, printWarpAction(warpToWorld));
+ Logger::info("UniverseServer: Warping player {} to {}", clientId, printWarpAction(warpToWorld));
if (auto toWorld = maybeToWorld.value()) {
if (toWorld->spawnTargetValid(warpToWorld.target)) {
if (auto currentWorld = clientContext->playerWorld()) {
@@ -795,21 +795,21 @@ void UniverseServer::warpPlayers() {
}
}
} else if (auto returnWarp = clientContext->playerReturnWarp()) {
- Logger::info("UniverseServer: Warping player %s failed, returning to '%s'", clientId, printWarpAction(returnWarp));
+ Logger::info("UniverseServer: Warping player {} failed, returning to '{}'", clientId, printWarpAction(returnWarp));
m_pendingPlayerWarps[clientId] = {returnWarp, false};
} else {
- Logger::info("UniverseServer: Warping player %s failed, returning to ship", clientId);
+ Logger::info("UniverseServer: Warping player {} failed, returning to ship", clientId);
m_pendingPlayerWarps[clientId] = {WarpAlias::OwnShip, false};
}
m_connectionServer->sendPackets(clientId, {make_shared<PlayerWarpResultPacket>(true, warpAction, false)});
m_pendingPlayerWarps.remove(clientId);
} else {
- Logger::info("UniverseServer: Warping player %s failed, invalid spawn target '%s'", clientId, printSpawnTarget(warpToWorld.target));
+ Logger::info("UniverseServer: Warping player {} failed, invalid spawn target '{}'", clientId, printSpawnTarget(warpToWorld.target));
m_connectionServer->sendPackets(clientId, {make_shared<PlayerWarpResultPacket>(false, warpAction, true)});
m_pendingPlayerWarps.remove(clientId);
}
} else {
- Logger::info("UniverseServer: Warping player %s failed, invalid world '%s' or world failed to load", clientId, printWorldId(warpToWorld.world));
+ Logger::info("UniverseServer: Warping player {} failed, invalid world '{}' or world failed to load", clientId, printWorldId(warpToWorld.world));
m_connectionServer->sendPackets(clientId, {make_shared<PlayerWarpResultPacket>(false, warpAction, false)});
m_pendingPlayerWarps.remove(clientId);
}
@@ -888,9 +888,9 @@ void UniverseServer::flyShips() {
}
if (destination.isNull())
- Logger::info("Flying ship for player %s to new starter world", clientId);
+ Logger::info("Flying ship for player {} to new starter world", clientId);
else
- Logger::info("Flying ship for player %s to %s", clientId, destination);
+ Logger::info("Flying ship for player {} to {}", clientId, destination);
bool startInWarp = system == Vec3I();
clientShip->executeAction([interstellar, startInWarp](WorldServerThread*, WorldServer* worldServer) {
@@ -946,7 +946,7 @@ void UniverseServer::arriveShips() {
if (!coordinate.isSystem() && !triggerWorldCreation(CelestialWorldId(coordinate)))
return false;
- Logger::info("UniverseServer: Arriving ship for player %s at %s", clientId, coordinate);
+ Logger::info("UniverseServer: Arriving ship for player {} at {}", clientId, coordinate);
// world is loaded, ship has arrived
clientContext->setShipCoordinate(coordinate);
@@ -996,7 +996,7 @@ void UniverseServer::processChat() {
if (auto clientContext = m_clients.get(p.first)) {
for (auto const& chat : p.second) {
if (clientContext->remoteAddress())
- Logger::info("Chat: <%s> %s", clientContext->playerName(), chat.first);
+ Logger::info("Chat: <{}> {}", clientContext->playerName(), chat.first);
auto team = m_teamManager->getTeam(clientContext->playerUuid());
if (chat.second == ChatSendMode::Broadcast)
@@ -1017,7 +1017,7 @@ void UniverseServer::clearBrokenWorlds() {
// Clear out all broken worlds
eraseWhere(m_worlds, [](auto const& p) {
if (!p.second.isValid()) {
- Logger::info("UniverseServer: Clearing broken world %s", p.first);
+ Logger::info("UniverseServer: Clearing broken world {}", p.first);
return true;
} else {
return false;
@@ -1038,7 +1038,7 @@ void UniverseServer::shutdownInactiveWorlds() {
if (auto world = getWorld(worldId)) {
if (world->serverErrorOccurred()) {
world->stop();
- Logger::error("UniverseServer: World %s has stopped due to an error", worldId);
+ Logger::error("UniverseServer: World {} has stopped due to an error", worldId);
worldDiedWithError(world->worldId());
} else if (world->clients().empty()) {
bool anyPendingWarps = false;
@@ -1049,7 +1049,7 @@ void UniverseServer::shutdownInactiveWorlds() {
}
}
if (!anyPendingWarps) {
- Logger::info("UniverseServer: Stopping idle world %s", worldId);
+ Logger::info("UniverseServer: Stopping idle world {}", worldId);
world->stop();
}
}
@@ -1057,7 +1057,7 @@ void UniverseServer::shutdownInactiveWorlds() {
if (world->isJoined()) {
auto kickClients = world->clients();
if (!kickClients.empty()) {
- Logger::info("UniverseServer: World %s shutdown, kicking %s players to their own ships", worldId, world->clients().size());
+ Logger::info("UniverseServer: World {} shutdown, kicking {} players to their own ships", worldId, world->clients().size());
for (auto clientId : world->clients())
clientWarpPlayer(clientId, WarpAlias::OwnShip);
}
@@ -1089,7 +1089,7 @@ void UniverseServer::shutdownInactiveWorlds() {
eraseWhere(m_tempWorldIndex, [this, systemLocationWorlds](pair<InstanceWorldId, pair<uint64_t, uint64_t>> const& p) {
String storageFile = tempWorldFile(p.first);
if (!m_worlds.contains(WorldId(p.first)) && !systemLocationWorlds.contains(p.first) && m_universeClock->milliseconds() > int64_t(p.second.first + p.second.second)) {
- Logger::info("UniverseServer: Expiring temporary world %s", printWorldId(p.first));
+ Logger::info("UniverseServer: Expiring temporary world {}", printWorldId(p.first));
if (File::isFile(storageFile))
File::remove(storageFile);
return true;
@@ -1117,7 +1117,7 @@ void UniverseServer::doTriggeredStorage() {
p.second->updateShipChunks(shipWorld->readChunks());
auto versioningDatabase = Root::singleton().versioningDatabase();
- String clientContextFile = File::relativeTo(m_storageDirectory, strf("%s.clientcontext", p.second->playerUuid().hex()));
+ String clientContextFile = File::relativeTo(m_storageDirectory, strf("{}.clientcontext", p.second->playerUuid().hex()));
VersionedJson::writeFile(versioningDatabase->makeCurrentVersionedJson("ClientContext", p.second->storeServerData()), clientContextFile);
}
@@ -1153,8 +1153,8 @@ void UniverseServer::loadSettings() {
m_universeClock = make_shared<Clock>();
m_universeClock->setTime(settings.getDouble("time"));
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load universe settings file, loading defaults %s", outputException(e, false));
- File::rename(storageFile, strf("%s.%s.fail", storageFile, Time::millisecondsSinceEpoch()));
+ Logger::error("UniverseServer: Could not load universe settings file, loading defaults {}", outputException(e, false));
+ File::rename(storageFile, strf("{}.{}.fail", storageFile, Time::millisecondsSinceEpoch()));
loadDefaultSettings();
}
} else {
@@ -1237,7 +1237,7 @@ Maybe<CelestialCoordinate> UniverseServer::nextStarterWorld() {
});
if (randomWorld)
- Logger::info("UniverseServer: Found randomized starter world at %s", *randomWorld);
+ Logger::info("UniverseServer: Found randomized starter world at {}", *randomWorld);
else
Logger::error("UniverseServer: Could not find randomized starter world!");
@@ -1262,7 +1262,7 @@ void UniverseServer::loadTempWorldIndex() {
}
} catch (std::exception const& e) {
Logger::error("UniverseServer: Could not load temp world index file", outputException(e, false));
- File::rename(storageFile, strf("%s.%s.fail", storageFile, Time::millisecondsSinceEpoch()));
+ File::rename(storageFile, strf("{}.{}.fail", storageFile, Time::millisecondsSinceEpoch()));
}
}
@@ -1272,7 +1272,7 @@ void UniverseServer::loadTempWorldIndex() {
if (p.second == false && p.first.endsWith(".tempworld")) {
String storageFile = File::relativeTo(m_storageDirectory, p.first);
if (!tempWorldFiles.contains(storageFile)) {
- Logger::info("UniverseServer: Removing unindexed temporary world %s", p.first);
+ Logger::info("UniverseServer: Removing unindexed temporary world {}", p.first);
File::remove(storageFile);
}
}
@@ -1293,10 +1293,10 @@ void UniverseServer::saveTempWorldIndex() {
String UniverseServer::tempWorldFile(InstanceWorldId const& worldId) const {
String identifier = worldId.instance;
if (worldId.uuid)
- identifier = strf("%s-%s", identifier, worldId.uuid->hex());
+ identifier = strf("{}-{}", identifier, worldId.uuid->hex());
if (worldId.level)
- identifier = strf("%s-%s", identifier, worldId.level.value());
- return File::relativeTo(m_storageDirectory, strf("%s.tempworld", identifier));
+ identifier = strf("{}-{}", identifier, worldId.level.value());
+ return File::relativeTo(m_storageDirectory, strf("{}.tempworld", identifier));
}
Maybe<String> UniverseServer::isBannedUser(Maybe<HostAddress> hostAddress, Uuid playerUuid) const {
@@ -1476,7 +1476,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
}
if (protocolRequest->requestProtocolVersion != StarProtocolVersion) {
- Logger::warn("UniverseServer: client connection aborted, unsupported protocol version %s, supported version %s",
+ Logger::warn("UniverseServer: client connection aborted, unsupported protocol version {}, supported version {}",
protocolRequest->requestProtocolVersion, StarProtocolVersion);
connection.pushSingle(make_shared<ProtocolResponsePacket>(false));
connection.sendAll(clientWaitLimit);
@@ -1500,11 +1500,11 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
bool administrator = false;
- String accountString = !clientConnect->account.empty() ? strf("'%s'", clientConnect->account) : "<anonymous>";
+ String accountString = !clientConnect->account.empty() ? strf("'{}'", clientConnect->account) : "<anonymous>";
String remoteAddressString = remoteAddress ? toString(*remoteAddress) : "local";
auto connectionFail = [&](String message) {
- Logger::warn("UniverseServer: Login attempt failed with account '%s' as player '%s' from address %s, error: %s",
+ Logger::warn("UniverseServer: Login attempt failed with account '{}' as player '{}' from address {}, error: {}",
accountString, clientConnect->playerName, remoteAddressString, message);
connection.pushSingle(make_shared<ConnectFailurePacket>(move(message)));
mainLocker.lock();
@@ -1513,7 +1513,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
if (!remoteAddress) {
administrator = true;
- Logger::info("UniverseServer: Logged in player '%s' locally", clientConnect->playerName);
+ Logger::info("UniverseServer: Logged in player '{}' locally", clientConnect->playerName);
} else {
if (clientConnect->assetsDigest != m_assetsDigest) {
if (!configuration->get("allowAssetsMismatch").toBool()) {
@@ -1555,7 +1555,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
// prevent account detection, overkill given the overall level of
// security but hey, why not.
if (!success) {
- connectionFail(strf("No such account '%s' or incorrect password", clientConnect->account));
+ connectionFail(strf("No such account '{}' or incorrect password", clientConnect->account));
return;
}
} else {
@@ -1572,7 +1572,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
}
}
- Logger::info("UniverseServer: Logged in account '%s' as player '%s' from address %s",
+ Logger::info("UniverseServer: Logged in account '{}' as player '{}' from address {}",
accountString, clientConnect->playerName, remoteAddressString);
mainLocker.lock();
@@ -1599,15 +1599,15 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
clientContext->registerRpcHandlers(m_teamManager->rpcHandlers());
- String clientContextFile = File::relativeTo(m_storageDirectory, strf("%s.clientcontext", clientConnect->playerUuid.hex()));
+ String clientContextFile = File::relativeTo(m_storageDirectory, strf("{}.clientcontext", clientConnect->playerUuid.hex()));
if (File::isFile(clientContextFile)) {
try {
auto contextStore = versioningDatabase->loadVersionedJson(VersionedJson::readFile(clientContextFile), "ClientContext");
clientContext->loadServerData(contextStore);
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load client context file for <User: %s>, ignoring! %s",
+ Logger::error("UniverseServer: Could not load client context file for <User: {}>, ignoring! {}",
clientConnect->playerName, outputException(e, false));
- File::rename(clientContextFile, strf("%s.%s.fail", clientContextFile, Time::millisecondsSinceEpoch()));
+ File::rename(clientContextFile, strf("{}.{}.fail", clientContextFile, Time::millisecondsSinceEpoch()));
}
}
@@ -1637,7 +1637,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
Json introInstance = assets->json("/universe_server.config:introInstance");
String speciesIntroInstance = introInstance.getString(clientConnect->playerSpecies, introInstance.getString("default", ""));
if (!speciesIntroInstance.empty() && !clientConnect->introComplete) {
- Logger::info("UniverseServer: Spawning player in intro instance %s", speciesIntroInstance);
+ Logger::info("UniverseServer: Spawning player in intro instance {}", speciesIntroInstance);
WarpAction introWarp = WarpToWorld{InstanceWorldId(speciesIntroInstance, clientContext->playerUuid()), {}};
clientWarpPlayer(clientId, introWarp);
} else if (auto reviveWarp = clientContext->playerReviveWarp()) {
@@ -1655,7 +1655,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
useReviveWarp = false;
if (useReviveWarp) {
- Logger::info("UniverseServer: Reviving player at %s", reviveWarp.world);
+ Logger::info("UniverseServer: Reviving player at {}", reviveWarp.world);
clientWarpPlayer(clientId, reviveWarp);
} else {
Logger::info("UniverseServer: Player revive position is expired, spawning back at own ship");
@@ -1667,7 +1667,7 @@ void UniverseServer::acceptConnection(UniverseConnection connection, Maybe<HostA
}
clientFlyShip(clientId, clientContext->shipCoordinate().location(), clientContext->shipLocation());
- Logger::info("UniverseServer: Client %s connected", clientContext->descriptiveName());
+ Logger::info("UniverseServer: Client {} connected", clientContext->descriptiveName());
auto players = static_cast<uint16_t>(m_clients.size());
for (auto clientId : m_clients.keys()) {
@@ -1763,12 +1763,12 @@ void UniverseServer::doDisconnection(ConnectionId clientId, String const& reason
// Write the final client context.
auto versioningDatabase = Root::singleton().versioningDatabase();
- String clientContextFile = File::relativeTo(m_storageDirectory, strf("%s.clientcontext", clientContext->playerUuid().hex()));
+ String clientContextFile = File::relativeTo(m_storageDirectory, strf("{}.clientcontext", clientContext->playerUuid().hex()));
VersionedJson::writeFile(versioningDatabase->makeCurrentVersionedJson("ClientContext", clientContext->storeServerData()), clientContextFile);
m_clients.remove(clientId);
m_deadConnections.append({m_connectionServer->removeConnection(clientId), Time::monotonicMilliseconds()});
- Logger::info("UniverseServer: Client %s disconnected for reason: %s", clientContext->descriptiveName(), reason);
+ Logger::info("UniverseServer: Client {} disconnected for reason: {}", clientContext->descriptiveName(), reason);
auto players = static_cast<uint16_t>(m_clients.size());
for (auto clientId : m_clients.keys()) {
@@ -1798,7 +1798,7 @@ WorldServerThreadPtr UniverseServer::getWorld(WorldId const& worldId) {
return maybeWorldPromise->get();
} catch (std::exception const& e) {
maybeWorldPromise.reset();
- Logger::error("UniverseServer: error during world create: %s", outputException(e, true));
+ Logger::error("UniverseServer: error during world create: {}", outputException(e, true));
worldDiedWithError(worldId);
}
}
@@ -1821,7 +1821,7 @@ WorldServerThreadPtr UniverseServer::createWorld(WorldId const& worldId) {
return maybeWorldPromise->get();
} catch (std::exception const& e) {
maybeWorldPromise.reset();
- Logger::error("UniverseServer: error during world create: %s", outputException(e, true));
+ Logger::error("UniverseServer: error during world create: {}", outputException(e, true));
worldDiedWithError(worldId);
return {};
}
@@ -1849,7 +1849,7 @@ Maybe<WorldServerThreadPtr> UniverseServer::triggerWorldCreation(WorldId const&
return maybeWorldPromise->get();
} catch (std::exception const& e) {
maybeWorldPromise.reset();
- Logger::error("UniverseServer: error during world create: %s", outputException(e, true));
+ Logger::error("UniverseServer: error during world create: {}", outputException(e, true));
worldDiedWithError(worldId);
return WorldServerThreadPtr();
}
@@ -1884,16 +1884,16 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::shipWorldPromise(
auto shipChunks = clientContext->shipChunks();
if (!shipChunks.empty()) {
try {
- Logger::info("UniverseServer: Loading client ship world %s", clientShipWorldId);
+ Logger::info("UniverseServer: Loading client ship world {}", clientShipWorldId);
shipWorld = make_shared<WorldServer>(shipChunks);
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load client ship %s, resetting ship to default state! %s",
+ Logger::error("UniverseServer: Could not load client ship {}, resetting ship to default state! {}",
clientShipWorldId, outputException(e, false));
}
}
if (!shipWorld) {
- Logger::info("UniverseServer: Creating new client ship world %s", clientShipWorldId);
+ Logger::info("UniverseServer: Creating new client ship world {}", clientShipWorldId);
shipWorld = make_shared<WorldServer>(Vec2U(2048, 2048), File::ephemeralFile());
auto shipStructure = WorldStructure(speciesShips.get(clientContext->playerSpecies()).first());
shipStructure = shipWorld->setCentralStructure(shipStructure);
@@ -1940,20 +1940,20 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::celestialWorldPro
return m_workerPool.addProducer<WorldServerThreadPtr>([this, celestialWorldId, storageDirectory, celestialDatabase, universeClock]() {
WorldServerPtr worldServer;
- String storageFile = File::relativeTo(storageDirectory, strf("%s.world", celestialWorldId.filename()));
+ String storageFile = File::relativeTo(storageDirectory, strf("{}.world", celestialWorldId.filename()));
if (File::isFile(storageFile)) {
try {
- Logger::info("UniverseServer: Loading celestial world %s", celestialWorldId);
+ Logger::info("UniverseServer: Loading celestial world {}", celestialWorldId);
worldServer = make_shared<WorldServer>(File::open(storageFile, IOMode::ReadWrite));
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load celestial world %s, removing! Cause: %s",
+ Logger::error("UniverseServer: Could not load celestial world {}, removing! Cause: {}",
celestialWorldId, outputException(e, false));
- File::rename(storageFile, strf("%s.%s.fail", storageFile, Time::millisecondsSinceEpoch()));
+ File::rename(storageFile, strf("{}.{}.fail", storageFile, Time::millisecondsSinceEpoch()));
}
}
if (!worldServer) {
- Logger::info("UniverseServer: Creating celestial world %s", celestialWorldId);
+ Logger::info("UniverseServer: Creating celestial world {}", celestialWorldId);
auto worldTemplate = make_shared<WorldTemplate>(celestialWorldId, celestialDatabase);
worldServer = make_shared<WorldServer>(worldTemplate, File::open(storageFile, IOMode::ReadWrite | IOMode::Truncate));
}
@@ -1990,7 +1990,7 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::instanceWorldProm
else if (worldType.equalsIgnoreCase("FloatingDungeon"))
worldParameters = generateFloatingDungeonWorldParameters(worldConfig.getString("dungeonWorld"));
else
- throw UniverseServerException(strf("Unknown world type: '%s'\n", worldType));
+ throw UniverseServerException(strf("Unknown world type: '{}'\n", worldType));
if (instanceWorldId.level)
worldParameters->threatLevel = *instanceWorldId.level;
@@ -2013,24 +2013,24 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::instanceWorldProm
if (persistent) {
String identifier = instanceWorldId.instance;
if (instanceWorldId.uuid)
- identifier = strf("%s-%s", identifier, instanceWorldId.uuid->hex());
+ identifier = strf("{}-{}", identifier, instanceWorldId.uuid->hex());
if (instanceWorldId.level)
- identifier = strf("%s-%s", identifier, instanceWorldId.level.value());
- String storageFile = File::relativeTo(storageDirectory, strf("unique-%s.world", identifier));
+ identifier = strf("{}-{}", identifier, instanceWorldId.level.value());
+ String storageFile = File::relativeTo(storageDirectory, strf("unique-{}.world", identifier));
if (File::isFile(storageFile)) {
try {
- Logger::info("UniverseServer: Loading persistent unique instance world %s", instanceWorldId.instance);
+ Logger::info("UniverseServer: Loading persistent unique instance world {}", instanceWorldId.instance);
worldServer = make_shared<WorldServer>(File::open(storageFile, IOMode::ReadWrite));
worldExisted = true;
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load persistent unique instance world %s, removing! Cause: %s",
+ Logger::error("UniverseServer: Could not load persistent unique instance world {}, removing! Cause: {}",
instanceWorldId.instance, outputException(e, false));
- File::rename(storageFile, strf("%s.%s.fail", storageFile, Time::millisecondsSinceEpoch()));
+ File::rename(storageFile, strf("{}.{}.fail", storageFile, Time::millisecondsSinceEpoch()));
}
}
if (!worldServer) {
- Logger::info("UniverseServer: Creating persistent unique instance world %s", instanceWorldId.instance);
+ Logger::info("UniverseServer: Creating persistent unique instance world {}", instanceWorldId.instance);
worldServer = make_shared<WorldServer>(worldTemplate, File::open(storageFile, IOMode::ReadWrite | IOMode::Truncate));
}
} else {
@@ -2040,12 +2040,12 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::instanceWorldProm
if (m_tempWorldIndex.contains(instanceWorldId)) {
auto file = File::open(storageFile, IOMode::ReadWrite);
if (file->size() > 0) {
- Logger::info("UniverseServer: Loading temporary instance world %s from storage", instanceWorldId);
+ Logger::info("UniverseServer: Loading temporary instance world {} from storage", instanceWorldId);
try {
worldServer = make_shared<WorldServer>(file);
worldExisted = true;
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Could not load temporary instance world '%s', re-creating cause: %s",
+ Logger::error("UniverseServer: Could not load temporary instance world '{}', re-creating cause: {}",
instanceWorldId, outputException(e, false));
}
}
@@ -2055,7 +2055,7 @@ Maybe<WorkerPoolPromise<WorldServerThreadPtr>> UniverseServer::instanceWorldProm
}
if (!worldServer) {
- Logger::info("UniverseServer: Creating temporary instance world '%s' with expiry time %s", instanceWorldId, deleteTime);
+ Logger::info("UniverseServer: Creating temporary instance world '{}' with expiry time {}", instanceWorldId, deleteTime);
worldServer = make_shared<WorldServer>(worldTemplate, File::open(storageFile, IOMode::ReadWrite));
m_tempWorldIndex.set(instanceWorldId, pair<uint64_t, uint64_t>(m_universeClock->milliseconds(), deleteTime));
@@ -2092,10 +2092,10 @@ SystemWorldServerThreadPtr UniverseServer::createSystemWorld(Vec3I const& locati
if (!m_systemWorlds.contains(location)) {
SystemWorldServerPtr systemWorld;
- String storageFile = File::relativeTo(m_storageDirectory, strf("%s_%s_%s.system", location[0], location[1], location[2]));
+ String storageFile = File::relativeTo(m_storageDirectory, strf("{}_{}_{}.system", location[0], location[1], location[2]));
bool loadedFromStorage = false;
if (File::isFile(storageFile)) {
- Logger::info("UniverseServer: Loading system world %s from disk storage", location);
+ Logger::info("UniverseServer: Loading system world {} from disk storage", location);
try {
auto versioningDatabase = Root::singleton().versioningDatabase();
VersionedJson versionedStore = VersionedJson::readFile(storageFile);
@@ -2104,14 +2104,14 @@ SystemWorldServerThreadPtr UniverseServer::createSystemWorld(Vec3I const& locati
systemWorld = make_shared<SystemWorldServer>(store, m_universeClock, m_celestialDatabase);
loadedFromStorage = true;
} catch (std::exception const& e) {
- Logger::error("UniverseServer: Failed to load system %s from disk storage, re-creating. Cause: %s", location, outputException(e, false));
- File::rename(storageFile, strf("%s.%s.fail", storageFile, Time::millisecondsSinceEpoch()));
+ Logger::error("UniverseServer: Failed to load system {} from disk storage, re-creating. Cause: {}", location, outputException(e, false));
+ File::rename(storageFile, strf("{}.{}.fail", storageFile, Time::millisecondsSinceEpoch()));
loadedFromStorage = false;
}
}
if (!loadedFromStorage) {
- Logger::info("UniverseServer: Creating new system world at location %s", location);
+ Logger::info("UniverseServer: Creating new system world at location {}", location);
systemWorld = make_shared<SystemWorldServer>(location, m_universeClock, m_celestialDatabase);
}
@@ -2125,7 +2125,7 @@ SystemWorldServerThreadPtr UniverseServer::createSystemWorld(Vec3I const& locati
}
bool UniverseServer::instanceWorldStoredOrActive(InstanceWorldId const& worldId) const {
- String storageFile = File::relativeTo(m_storageDirectory, strf("unique-%s.world", worldId.instance));
+ String storageFile = File::relativeTo(m_storageDirectory, strf("unique-{}.world", worldId.instance));
return m_worlds.value(worldId).isValid() || m_tempWorldIndex.contains(worldId) || File::isFile(storageFile);
}
diff --git a/source/game/StarUniverseSettings.cpp b/source/game/StarUniverseSettings.cpp
index b9e4970..30e8b6e 100644
--- a/source/game/StarUniverseSettings.cpp
+++ b/source/game/StarUniverseSettings.cpp
@@ -15,7 +15,7 @@ UniverseFlagAction parseUniverseFlagAction(Json const& json) {
res.targetPosition = jsonToVec2I(json.get("targetPosition"));
return res;
} else {
- throw StarException(strf("Unsupported universe flag action type %s", actionType));
+ throw StarException(strf("Unsupported universe flag action type {}", actionType));
}
}
@@ -53,11 +53,11 @@ void UniverseSettings::setFlag(String const& flag) {
MutexLocker locker(m_lock);
if (m_flags.add(flag)) {
- Logger::info("Universe flags set to %s", m_flags);
+ Logger::info("Universe flags set to {}", m_flags);
if (auto flagActions = m_flagActions.maybe(flag))
m_pendingFlagActions.appendAll(*flagActions);
else
- Logger::info("No actions configured for universe flag %s", flag);
+ Logger::info("No actions configured for universe flag {}", flag);
}
}
diff --git a/source/game/StarVehicleDatabase.cpp b/source/game/StarVehicleDatabase.cpp
index cb1a302..4c22963 100644
--- a/source/game/StarVehicleDatabase.cpp
+++ b/source/game/StarVehicleDatabase.cpp
@@ -16,11 +16,11 @@ VehicleDatabase::VehicleDatabase() {
String name = config.getString("name");
if (m_vehicles.contains(name))
- throw VehicleDatabaseException::format("Repeat vehicle name '%s'", name);
+ throw VehicleDatabaseException::format("Repeat vehicle name '{}'", name);
m_vehicles.add(move(name), make_pair(move(file), move(config)));
} catch (StarException const& e) {
- throw VehicleDatabaseException(strf("Error loading vehicle '%s'", file), e);
+ throw VehicleDatabaseException(strf("Error loading vehicle '{}'", file), e);
}
}
}
@@ -28,7 +28,7 @@ VehicleDatabase::VehicleDatabase() {
VehiclePtr VehicleDatabase::create(String const& vehicleName, Json const& extraConfig) const {
auto configPair = m_vehicles.ptr(vehicleName);
if (!configPair)
- throw VehicleDatabaseException::format("No such vehicle named '%s'", vehicleName);
+ throw VehicleDatabaseException::format("No such vehicle named '{}'", vehicleName);
return make_shared<Vehicle>(configPair->second, configPair->first, extraConfig);
}
diff --git a/source/game/StarVersioningDatabase.cpp b/source/game/StarVersioningDatabase.cpp
index aa47db7..0ff46fe 100644
--- a/source/game/StarVersioningDatabase.cpp
+++ b/source/game/StarVersioningDatabase.cpp
@@ -23,7 +23,7 @@ VersionedJson VersionedJson::readFile(String const& filename) {
DataStreamIODevice ds(File::open(filename, IOMode::Read));
if (ds.readBytes(MagicStringSize) != ByteArray(Magic, MagicStringSize))
- throw IOException(strf("Wrong magic bytes at start of versioned json file, expected '%s'", Magic));
+ throw IOException(strf("Wrong magic bytes at start of versioned json file, expected '{}'", Magic));
return ds.read<VersionedJson>();
}
@@ -59,7 +59,7 @@ bool VersionedJson::empty() const {
void VersionedJson::expectIdentifier(String const& expectedIdentifier) const {
if (identifier != expectedIdentifier)
- throw VersionedJsonException::format("VersionedJson identifier mismatch, expected '%s' but got '%s'", expectedIdentifier, identifier);
+ throw VersionedJsonException::format("VersionedJson identifier mismatch, expected '{}' but got '{}'", expectedIdentifier, identifier);
}
DataStream& operator>>(DataStream& ds, VersionedJson& versionedJson) {
@@ -91,7 +91,7 @@ VersioningDatabase::VersioningDatabase() {
try {
auto scriptParts = File::baseName(scriptFile).splitAny("_.");
if (scriptParts.size() != 4)
- throw VersioningDatabaseException::format("Script file '%s' filename not of the form <identifier>_<fromversion>_<toversion>.lua", scriptFile);
+ throw VersioningDatabaseException::format("Script file '{}' filename not of the form <identifier>_<fromversion>_<toversion>.lua", scriptFile);
String identifier = scriptParts.at(0);
VersionNumber fromVersion = lexicalCast<VersionNumber>(scriptParts.at(1));
@@ -99,7 +99,7 @@ VersioningDatabase::VersioningDatabase() {
m_versionUpdateScripts[identifier.toLower()].append({scriptFile, fromVersion, toVersion});
} catch (StarException const&) {
- throw VersioningDatabaseException::format("Error parsing version information from versioning script '%s'", scriptFile);
+ throw VersioningDatabaseException::format("Error parsing version information from versioning script '{}'", scriptFile);
}
}
@@ -135,7 +135,7 @@ VersionedJson VersioningDatabase::updateVersionedJson(VersionedJson const& versi
VersionedJson result = versionedJson;
Maybe<VersionNumber> targetVersion = m_currentVersions.maybe(versionedJson.identifier);
if (!targetVersion)
- throw VersioningDatabaseException::format("Versioned JSON has an unregistered identifier '%s'", versionedJson.identifier);
+ throw VersioningDatabaseException::format("Versioned JSON has an unregistered identifier '{}'", versionedJson.identifier);
LuaCallbacks celestialCallbacks;
celestialCallbacks.registerCallback("parameters", [&celestialDatabase](Json const& coord) {
@@ -158,28 +158,28 @@ VersionedJson VersioningDatabase::updateVersionedJson(VersionedJson const& versi
result.content = scriptContext.invokePath<Json>("update", result.content);
if (!result.content) {
throw VersioningDatabaseException::format(
- "Could not bring versionedJson with identifier '%s' and version %s forward to current version of %s, conversion script from %s to %s returned null (un-upgradeable)",
+ "Could not bring versionedJson with identifier '{}' and version {} forward to current version of {}, conversion script from {} to {} returned null (un-upgradeable)",
versionedJson.identifier, result.version, targetVersion, updateScript.fromVersion, updateScript.toVersion);
}
- Logger::debug("Brought versionedJson '%s' from version %s to %s",
+ Logger::debug("Brought versionedJson '{}' from version {} to {}",
versionedJson.identifier, result.version, updateScript.toVersion);
result.version = updateScript.toVersion;
}
}
} catch (std::exception const& e) {
- throw VersioningDatabaseException(strf("Could not bring versionedJson with identifier '%s' and version %s forward to current version of %s",
+ throw VersioningDatabaseException(strf("Could not bring versionedJson with identifier '{}' and version {} forward to current version of {}",
versionedJson.identifier, result.version, targetVersion), e);
}
if (result.version > *targetVersion) {
throw VersioningDatabaseException::format(
- "VersionedJson with identifier '%s' and version %s is newer than current version of %s, cannot load",
+ "VersionedJson with identifier '{}' and version {} is newer than current version of {}, cannot load",
versionedJson.identifier, result.version, targetVersion);
}
if (result.version != *targetVersion) {
throw VersioningDatabaseException::format(
- "Could not bring VersionedJson with identifier '%s' and version %s forward to current version of %s, best version was %s",
+ "Could not bring VersionedJson with identifier '{}' and version {} forward to current version of {}, best version was {}",
versionedJson.identifier, result.version, targetVersion, result.version);
}
@@ -208,7 +208,7 @@ LuaCallbacks VersioningDatabase::makeVersioningCallbacks() const {
return updateVersionedJson(loadedJson).content;
} catch (IOException const& e) {
Logger::debug(
- "Unable to load versioned JSON file %s in versioning script: %s", storagePath, outputException(e, false));
+ "Unable to load versioned JSON file {} in versioning script: {}", storagePath, outputException(e, false));
return Json();
}
});
diff --git a/source/game/StarWarping.cpp b/source/game/StarWarping.cpp
index aa615b4..442d18e 100644
--- a/source/game/StarWarping.cpp
+++ b/source/game/StarWarping.cpp
@@ -50,11 +50,11 @@ String printWorldId(WorldId const& worldId) {
String uuidPart = instanceWorldId->uuid ? instanceWorldId->uuid->hex() : "-";
String levelPart = instanceWorldId->level ? toString(*instanceWorldId->level) : "-";
- return strf("InstanceWorld:%s:%s:%s", instanceWorldId->instance, uuidPart, levelPart);
+ return strf("InstanceWorld:{}:{}:{}", instanceWorldId->instance, uuidPart, levelPart);
} else if (auto celestialWorldId = worldId.ptr<CelestialWorldId>()) {
- return strf("CelestialWorld:%s", *celestialWorldId);
+ return strf("CelestialWorld:{}", *celestialWorldId);
} else if (auto clientShipWorldId = worldId.ptr<ClientShipWorldId>()) {
- return strf("ClientShipWorld:%s", clientShipWorldId->hex());
+ return strf("ClientShipWorld:{}", clientShipWorldId->hex());
} else {
return "Nowhere";
}
@@ -98,7 +98,7 @@ WorldId parseWorldId(String const& printedId) {
} else if (type.equalsIgnoreCase("Nowhere")) {
return {};
} else {
- throw StarException::format("Improper WorldId type '%s'", type);
+ throw StarException::format("Improper WorldId type '{}'", type);
}
}
@@ -149,7 +149,7 @@ String printSpawnTarget(SpawnTarget spawnTarget) {
if (auto str = spawnTarget.ptr<SpawnTargetUniqueEntity>())
return *str;
else if (auto pos = spawnTarget.ptr<SpawnTargetPosition>())
- return strf("%s.%s", (*pos)[0], (*pos)[1]);
+ return strf("{}.{}", (*pos)[0], (*pos)[1]);
else if (auto x = spawnTarget.ptr<SpawnTargetX>())
return toString(x->t);
else
@@ -217,11 +217,11 @@ String printWarpAction(WarpAction const& warpAction) {
else if (*warpAlias == WarpAlias::OwnShip)
return "OwnShip";
} else if (auto warpToPlayer = warpAction.ptr<WarpToPlayer>()) {
- return strf("Player:%s", warpToPlayer->hex());
+ return strf("Player:{}", warpToPlayer->hex());
} else if (auto warpToWorld = warpAction.ptr<WarpToWorld>()) {
auto toWorldString = printWorldId(warpToWorld->world);
if (auto spawnTarget = warpToWorld->target)
- toWorldString = strf("%s=%s", toWorldString, printSpawnTarget(spawnTarget));
+ toWorldString = strf("{}={}", toWorldString, printSpawnTarget(spawnTarget));
return toWorldString;
}
diff --git a/source/game/StarWireProcessor.cpp b/source/game/StarWireProcessor.cpp
index 9b0d674..7c106af 100644
--- a/source/game/StarWireProcessor.cpp
+++ b/source/game/StarWireProcessor.cpp
@@ -50,7 +50,7 @@ void WireProcessor::populateWorking(WireEntity* wireEntity) {
auto p = m_workingWireEntities.insert(wireEntity->tilePosition(), WireEntityState{nullptr, {}, false});
if (!p.second) {
if (p.first->second.wireEntity != wireEntity)
- Logger::debug("Multiple wire entities share tile position: %s", wireEntity->position());
+ Logger::debug("Multiple wire entities share tile position: {}", wireEntity->position());
return;
}
auto& wes = p.first->second;
diff --git a/source/game/StarWorldClient.cpp b/source/game/StarWorldClient.cpp
index f04c70a..3e91779 100644
--- a/source/game/StarWorldClient.cpp
+++ b/source/game/StarWorldClient.cpp
@@ -641,18 +641,18 @@ void WorldClient::handleIncomingPackets(List<PacketPtr> const& packets) {
for (auto const& packet : packets) {
if (!inWorld() && !is<WorldStartPacket>(packet))
- Logger::error("WorldClient received packet type %s while not in world", PacketTypeNames.getRight(packet->type()));
+ Logger::error("WorldClient received packet type {} while not in world", PacketTypeNames.getRight(packet->type()));
if (auto worldStartPacket = as<WorldStartPacket>(packet)) {
initWorld(*worldStartPacket);
} else if (auto worldStopPacket = as<WorldStopPacket>(packet)) {
- Logger::info("Client received world stop packet, leaving: %s", worldStopPacket->reason);
+ Logger::info("Client received world stop packet, leaving: {}", worldStopPacket->reason);
clearWorld();
} else if (auto entityCreate = as<EntityCreatePacket>(packet)) {
if (m_entityMap->entity(entityCreate->entityId)) {
- Logger::error("WorldClient received entity create packet with duplicate entity id %s, deleting old entity.", entityCreate->entityId);
+ Logger::error("WorldClient received entity create packet with duplicate entity id {}, deleting old entity.", entityCreate->entityId);
removeEntity(entityCreate->entityId, false);
}
@@ -867,7 +867,7 @@ void WorldClient::handleIncomingPackets(List<PacketPtr> const& packets) {
m_latency = Time::monotonicMilliseconds() - m_pingTime.take();
} else {
- Logger::error("Improper packet type %s received by client", (int)packet->type());
+ Logger::error("Improper packet type {} received by client", (int)packet->type());
}
}
}
@@ -1031,7 +1031,7 @@ void WorldClient::update() {
renderCollisionDebug();
LogMap::set("client_entities", m_entityMap->size());
- LogMap::set("client_sectors", strf("%d", loadedSectors.size()));
+ LogMap::set("client_sectors", strf("{}", loadedSectors.size()));
LogMap::set("client_lua_mem", m_luaRoot->luaMemoryUsage());
}
@@ -1214,7 +1214,7 @@ void WorldClient::handleDamageNotifications() {
return;
Particle particle = Root::singleton().particleDatabase()->particle(damageNumberParticleKind);
particle.position += position;
- particle.string = particle.string.replace("$dmg$", strf("%s", displayValue));
+ particle.string = particle.string.replace("$dmg$", strf("{}", displayValue));
m_particles->add(particle);
};
diff --git a/source/game/StarWorldGeneration.cpp b/source/game/StarWorldGeneration.cpp
index 94a8664..301df08 100644
--- a/source/game/StarWorldGeneration.cpp
+++ b/source/game/StarWorldGeneration.cpp
@@ -196,7 +196,7 @@ void DungeonGeneratorWorld::markRegion(RectI const& region) {
if (!m_markForActivation)
return;
- Logger::debug("Marking %s as dungeon region", region);
+ Logger::debug("Marking {} as dungeon region", region);
m_worldServer->signalRegion(region);
m_worldServer->activateLiquidRegion(region);
@@ -206,7 +206,7 @@ void DungeonGeneratorWorld::markTerrain(PolyF const& region) {
if (!m_markForActivation)
return;
- Logger::debug("Marking poly as dungeon terrain region: %s", region);
+ Logger::debug("Marking poly as dungeon terrain region: {}", region);
m_worldServer->worldTemplate()->addCustomTerrainRegion(region);
}
@@ -214,7 +214,7 @@ void DungeonGeneratorWorld::markSpace(PolyF const& region) {
if (!m_markForActivation)
return;
- Logger::debug("Marking poly as dungeon space region: %s", region);
+ Logger::debug("Marking poly as dungeon space region: {}", region);
m_worldServer->worldTemplate()->addCustomSpaceRegion(region);
}
@@ -249,7 +249,7 @@ void DungeonGeneratorWorld::placeObject(Vec2I const& pos, String const& objectNa
if (auto object = objectDatabase->createForPlacement(m_worldServer, objectName, pos, direction, parameters))
m_worldServer->addEntity(object);
else
- Logger::warn("Failed to place dungeon object: %s direction: %s position: %s", objectName, (int)direction, pos);
+ Logger::warn("Failed to place dungeon object: {} direction: {} position: {}", objectName, (int)direction, pos);
}
void DungeonGeneratorWorld::placeVehicle(Vec2F const& pos, String const& vehicleName, Json const& parameters) {
@@ -421,7 +421,7 @@ void DungeonGeneratorWorld::spawnNpc(Vec2F const& position, Json const& paramete
monster->setPosition(position);
m_worldServer->addEntity(monster);
} else
- throw StarException(strf("Unknown spawnable kind '%s'", kind));
+ throw StarException(strf("Unknown spawnable kind '{}'", kind));
}
void DungeonGeneratorWorld::spawnStagehand(Vec2F const& position, Json const& definition) {
@@ -464,7 +464,7 @@ void DungeonGeneratorWorld::connectWireGroup(List<Vec2I> const& wireGroup) {
}
}
if (!found)
- Logger::warn("Dungeon wire endpoint not found. %s", entry);
+ Logger::warn("Dungeon wire endpoint not found. {}", entry);
}
if (!outbounds.size() || !inbounds.size()) {
@@ -673,7 +673,7 @@ void WorldGenerator::sectorLoadLevelChanged(WorldStorage* worldStorage, Sector c
}
void WorldGenerator::terraformSector(WorldStorage* worldStorage, Sector const& sector) {
- // Logger::info("terraforming sector %s...", sector);
+ // Logger::info("terraforming sector {}...", sector);
reapplyBiome(worldStorage, sector);
}
@@ -1161,7 +1161,7 @@ void WorldGenerator::reapplyBiome(WorldStorage* worldStorage, ServerTileSectorAr
auto tileArray = worldStorage->tileArray();
RectI sectorTiles = tileArray->sectorRegion(sector);
- // Logger::info("Reapplying biome in sector %s...", sectorTiles);
+ // Logger::info("Reapplying biome in sector {}...", sectorTiles);
auto entities = m_worldServer->entityQuery(RectF(sectorTiles.padded(1)));
List<TileEntityPtr> biomeTileEntities;
diff --git a/source/game/StarWorldLayout.cpp b/source/game/StarWorldLayout.cpp
index 5c6408c..58eca08 100644
--- a/source/game/StarWorldLayout.cpp
+++ b/source/game/StarWorldLayout.cpp
@@ -540,7 +540,7 @@ void WorldLayout::addBiomeRegion(
auto layerAndCell = findLayerAndCell(position[0], position[1]);
- // Logger::info("inserting biome %s into region with layerIndex %s cellIndex %s", biomeName, layerAndCell.first, layerAndCell.second);
+ // Logger::info("inserting biome {} into region with layerIndex {} cellIndex {}", biomeName, layerAndCell.first, layerAndCell.second);
auto targetLayer = m_layers[layerAndCell.first];
@@ -595,7 +595,7 @@ void WorldLayout::addBiomeRegion(
WorldRegionPtr newRegionPtr = make_shared<WorldRegion>(newRegion);
- // Logger::info("boundaries before region insertion are %s", targetLayer.boundaries);
+ // Logger::info("boundaries before region insertion are {}", targetLayer.boundaries);
// handle case where insert x position is exactly at world wrap
int insertX = position[0] > 0 ? position[0] : 1;
@@ -608,7 +608,7 @@ void WorldLayout::addBiomeRegion(
targetLayer.boundaries.insertAt(layerAndCell.second, insertX - 1);
targetLayer.cells.insertAt(layerAndCell.second, targetRegion);
- // Logger::info("boundaries after region insertion are %s", targetLayer.boundaries);
+ // Logger::info("boundaries after region insertion are {}", targetLayer.boundaries);
// expand the cell to the desired size
auto expandResult = expandRegionInLayer(targetLayer, layerAndCell.second + 1, width);
@@ -656,11 +656,11 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
// auto printRegionCells = [](List<RegionCell> const& cells) {
// String output = "";
// for (auto cell : cells)
- // output += strf("[%s %s] ", cell.lBound, cell.rBound);
+ // output += strf("[{} {}] ", cell.lBound, cell.rBound);
// return output;
// };
- // Logger::info("expanding region in layer with cellIndex %s newWidth %s", cellIndex, newWidth);
+ // Logger::info("expanding region in layer with cellIndex {} newWidth {}", cellIndex, newWidth);
List<RectI> regionRects;
@@ -669,7 +669,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
return {targetLayer, regionRects};
}
- // Logger::info("boundaries before expansion are %s", targetLayer.boundaries);
+ // Logger::info("boundaries before expansion are {}", targetLayer.boundaries);
// TODO: this is a messy way to get the top of the layer, but maybe it's ok
int layerTop = (int)m_worldSize[1];
@@ -707,7 +707,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
lastBoundary = nextBoundary;
}
- // Logger::info("before expansion:\ntarget cells are: %s\nother cells are: %s", printRegionCells(targetCells), printRegionCells(otherCells));
+ // Logger::info("before expansion:\ntarget cells are: {}\nother cells are: {}", printRegionCells(targetCells), printRegionCells(otherCells));
starAssert(targetCells.size() > 0);
starAssert(targetCells.size() < 3);
@@ -718,7 +718,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
currentWidth += (regionCell.rBound - regionCell.lBound);
if (currentWidth >= newWidth) {
- Logger::info("New cell width (%s) must be greater than current cell width %s!", newWidth, currentWidth);
+ Logger::info("New cell width ({}) must be greater than current cell width {}!", newWidth, currentWidth);
return {targetLayer, regionRects};
}
@@ -734,7 +734,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
targetCells[0].rBound += expandRight;
targetCells[targetCells.size() - 1].lBound -= expandLeft;
- // Logger::info("after expansion:\ntarget cells are: %s\nother cells are: %s", printRegionCells(targetCells), printRegionCells(otherCells));
+ // Logger::info("after expansion:\ntarget cells are: {}\nother cells are: {}", printRegionCells(targetCells), printRegionCells(otherCells));
// split any target cells that now cross the world wrap
List<RegionCell> wrappedTargetCells;
@@ -770,7 +770,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
otherCells = newOtherCells;
}
- // Logger::info("after de-overlapping:\ntarget cells are: %s\nother cells are: %s", printRegionCells(targetCells), printRegionCells(otherCells));
+ // Logger::info("after de-overlapping:\ntarget cells are: {}\nother cells are: {}", printRegionCells(targetCells), printRegionCells(otherCells));
// combine lists and sort
otherCells.appendAll(targetCells);
@@ -786,7 +786,7 @@ pair<WorldLayout::WorldLayer, List<RectI>> WorldLayout::expandRegionInLayer(Worl
}
}
- // Logger::info("boundaries after expansion are %s", targetLayer.boundaries);
+ // Logger::info("boundaries after expansion are {}", targetLayer.boundaries);
return {targetLayer, regionRects};
}
diff --git a/source/game/StarWorldParameters.cpp b/source/game/StarWorldParameters.cpp
index c1901c3..d0fc646 100644
--- a/source/game/StarWorldParameters.cpp
+++ b/source/game/StarWorldParameters.cpp
@@ -655,7 +655,7 @@ TerrestrialWorldParametersPtr generateTerrestrialWorldParameters(String const& t
parameters->surfaceLayer = surfaceLayer;
parameters->subsurfaceLayer = readLayer("subsurface").take();
- while (auto undergroundLayer = readLayer(strf("underground%s", parameters->undergroundLayers.size() + 1)))
+ while (auto undergroundLayer = readLayer(strf("underground{}", parameters->undergroundLayers.size() + 1)))
parameters->undergroundLayers.append(undergroundLayer.take());
parameters->coreLayer = readLayer("core").take();
diff --git a/source/game/StarWorldServer.cpp b/source/game/StarWorldServer.cpp
index 33fa74c..fd3f765 100644
--- a/source/game/StarWorldServer.cpp
+++ b/source/game/StarWorldServer.cpp
@@ -384,10 +384,10 @@ void WorldServer::handleIncomingPackets(ConnectionId clientId, List<PacketPtr> c
} else if (auto entityCreate = as<EntityCreatePacket>(packet)) {
if (!entityIdInSpace(entityCreate->entityId, clientInfo->clientId)) {
- throw WorldServerException::format("WorldServer received entity create packet with illegal entity id %s.", entityCreate->entityId);
+ throw WorldServerException::format("WorldServer received entity create packet with illegal entity id {}.", entityCreate->entityId);
} else {
if (m_entityMap->entity(entityCreate->entityId)) {
- Logger::error("WorldServer received duplicate entity create packet from client, deleting old entity %s", entityCreate->entityId);
+ Logger::error("WorldServer received duplicate entity create packet from client, deleting old entity {}", entityCreate->entityId);
removeEntity(entityCreate->entityId, false);
}
@@ -487,7 +487,7 @@ void WorldServer::handleIncomingPackets(ConnectionId clientId, List<PacketPtr> c
pair.second->outgoingPackets.append(make_shared<UpdateWorldPropertiesPacket>(updateWorldProperties->updatedProperties));
} else {
- throw WorldServerException::format("Improper packet type %s received by client", (int)packet->type());
+ throw WorldServerException::format("Improper packet type {} received by client", (int)packet->type());
}
}
}
@@ -610,12 +610,12 @@ void WorldServer::update() {
for (auto& pair : m_clientInfo)
pair.second->pendingForward = false;
- LogMap::set(strf("server_%s_entities", m_worldTemplate->worldSeed()), m_entityMap->size());
- LogMap::set(strf("server_%s_sectors", m_worldTemplate->worldSeed()), strf("%d", m_tileArray->loadedSectorCount()));
- LogMap::set(strf("server_%s_world_time", m_worldTemplate->worldSeed()), epochTime());
- LogMap::set(strf("server_%s_active_liquid", m_worldTemplate->worldSeed()), m_liquidEngine->activeCells());
- LogMap::set(strf("server_%s_day_time", m_worldTemplate->worldSeed()), timeOfDay() / dayLength());
- LogMap::set(strf("server_%s_lua_mem", m_worldTemplate->worldSeed()), m_luaRoot->luaMemoryUsage());
+ LogMap::set(strf("server_{}_entities", m_worldTemplate->worldSeed()), m_entityMap->size());
+ LogMap::set(strf("server_{}_sectors", m_worldTemplate->worldSeed()), strf("{}", m_tileArray->loadedSectorCount()));
+ LogMap::set(strf("server_{}_world_time", m_worldTemplate->worldSeed()), epochTime());
+ LogMap::set(strf("server_{}_active_liquid", m_worldTemplate->worldSeed()), m_liquidEngine->activeCells());
+ LogMap::set(strf("server_{}_day_time", m_worldTemplate->worldSeed()), timeOfDay() / dayLength());
+ LogMap::set(strf("server_{}_lua_mem", m_worldTemplate->worldSeed()), m_luaRoot->luaMemoryUsage());
}
WorldGeometry WorldServer::geometry() const {
@@ -1115,7 +1115,7 @@ void WorldServer::setTileProtection(DungeonId dungeonId, bool isProtected) {
pair.second->outgoingPackets.append(make_shared<UpdateTileProtectionPacket>(dungeonId, isProtected));
}
- Logger::info("Protected dungeonIds for world set to %s", m_protectedDungeonIds);
+ Logger::info("Protected dungeonIds for world set to {}", m_protectedDungeonIds);
}
void WorldServer::setTileProtectionEnabled(bool enabled) {
@@ -1212,7 +1212,7 @@ void WorldServer::init(bool firstTime) {
DungeonId currentDungeonId = 0;
for (auto const& dungeon : m_worldTemplate->dungeons()) {
- Logger::info("Placing dungeon %s", dungeon.dungeon);
+ Logger::info("Placing dungeon {}", dungeon.dungeon);
int retryCounter = m_serverConfig.getInt("spawnDungeonRetries");
while (retryCounter > 0) {
--retryCounter;
diff --git a/source/game/StarWorldServerThread.cpp b/source/game/StarWorldServerThread.cpp
index daa75e4..d3bcbc4 100644
--- a/source/game/StarWorldServerThread.cpp
+++ b/source/game/StarWorldServerThread.cpp
@@ -52,7 +52,7 @@ bool WorldServerThread::spawnTargetValid(SpawnTarget const& spawnTarget) {
RecursiveMutexLocker locker(m_mutex);
return m_worldServer->spawnTargetValid(spawnTarget);
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
return false;
}
@@ -68,7 +68,7 @@ bool WorldServerThread::addClient(ConnectionId clientId, SpawnTarget const& spaw
return false;
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
return false;
}
@@ -92,7 +92,7 @@ List<PacketPtr> WorldServerThread::removeClient(ConnectionId clientId) {
outgoingPackets.appendAll(m_worldServer->removeClient(clientId));
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
}
@@ -135,7 +135,7 @@ Maybe<Vec2F> WorldServerThread::playerRevivePosition(ConnectionId clientId) cons
return player->position() + player->feetOffset();
return {};
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
return {};
}
@@ -146,7 +146,7 @@ Maybe<pair<String, String>> WorldServerThread::pullNewPlanetType() {
RecursiveMutexLocker locker(m_mutex);
return m_worldServer->pullNewPlanetType();
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
return {};
}
@@ -167,7 +167,7 @@ WorldChunks WorldServerThread::readChunks() {
RecursiveMutexLocker locker(m_mutex);
return m_worldServer->readChunks();
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
return {};
}
@@ -194,8 +194,8 @@ void WorldServerThread::run() {
while (!m_stop && !m_errorOccurred) {
auto fidelity = lockedFidelity.value(automaticFidelity);
- LogMap::set(strf("server_%s_fidelity", m_worldId), WorldServerFidelityNames.getRight(fidelity));
- LogMap::set(strf("server_%s_update_fps", m_worldId), tickApproacher.rate());
+ LogMap::set(strf("server_{}_fidelity", m_worldId), WorldServerFidelityNames.getRight(fidelity));
+ LogMap::set(strf("server_{}_update_fps", m_worldId), tickApproacher.rate());
update(fidelity);
tickApproacher.tick();
@@ -225,7 +225,7 @@ void WorldServerThread::run() {
Thread::sleepPrecise(spareMilliseconds);
}
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught: %s", outputException(e, true));
+ Logger::error("WorldServerThread exception caught: {}", outputException(e, true));
m_errorOccurred = true;
}
}
@@ -240,7 +240,7 @@ void WorldServerThread::update(WorldServerFidelity fidelity) {
try {
m_worldServer->handleIncomingPackets(clientId, move(incomingPackets));
} catch (std::exception const& e) {
- Logger::error("WorldServerThread exception caught handling incoming packets for client %s: %s",
+ Logger::error("WorldServerThread exception caught handling incoming packets for client {}: {}",
clientId, outputException(e, true));
RecursiveMutexLocker queueLocker(m_queueMutex);
m_outgoingPacketQueue[clientId].appendAll(m_worldServer->removeClient(clientId));
@@ -264,7 +264,7 @@ void WorldServerThread::update(WorldServerFidelity fidelity) {
void WorldServerThread::sync() {
RecursiveMutexLocker locker(m_mutex);
- Logger::debug("WorldServer: periodic sync to disk of world %s", m_worldId);
+ Logger::debug("WorldServer: periodic sync to disk of world {}", m_worldId);
m_worldServer->sync();
}
diff --git a/source/game/StarWorldStorage.cpp b/source/game/StarWorldStorage.cpp
index 395bffd..869a830 100644
--- a/source/game/StarWorldStorage.cpp
+++ b/source/game/StarWorldStorage.cpp
@@ -157,7 +157,7 @@ void WorldStorage::loadSector(Sector sector) {
} catch (std::exception const& e) {
m_db.rollback();
m_db.close();
- throw WorldStorageException(strf("Failed to load sector %s", sector), e);
+ throw WorldStorageException(strf("Failed to load sector {}", sector), e);
}
}
@@ -168,7 +168,7 @@ void WorldStorage::activateSector(Sector sector) {
} catch (std::exception const& e) {
m_db.rollback();
m_db.close();
- throw WorldStorageException(strf("Failed to load sector %s", sector), e);
+ throw WorldStorageException(strf("Failed to load sector {}", sector), e);
}
}
@@ -193,12 +193,12 @@ void WorldStorage::triggerTerraformSector(Sector sector) {
p->generationLevel = SectorGenerationLevel::Terraform;
} else {
- throw WorldStorageException(strf("Couldn't flag sector %s for terraforming; metadata unavailable", sector));
+ throw WorldStorageException(strf("Couldn't flag sector {} for terraforming; metadata unavailable", sector));
}
} catch (std::exception const& e) {
m_db.rollback();
m_db.close();
- throw WorldStorageException(strf("Failed to terraform sector %s", sector), e);
+ throw WorldStorageException(strf("Failed to terraform sector {}", sector), e);
}
}
@@ -691,7 +691,7 @@ void WorldStorage::loadSectorToLevel(Sector const& sector, SectorLoadLevel targe
try {
addedEntities.append(entityFactory->loadVersionedEntity(entityStore));
} catch (std::exception const& e) {
- Logger::warn("Failed to deserialize entity: %s", outputException(e, true));
+ Logger::warn("Failed to deserialize entity: {}", outputException(e, true));
}
}
}
diff --git a/source/game/StarWorldStructure.cpp b/source/game/StarWorldStructure.cpp
index a014023..110d28b 100644
--- a/source/game/StarWorldStructure.cpp
+++ b/source/game/StarWorldStructure.cpp
@@ -101,7 +101,7 @@ WorldStructure::WorldStructure(String const& configPath) {
if (blockKey.anchor) {
if (anchorPosition)
throw WorldStructureException(
- strf("Multiple anchor points defined in blockImage, first point is at %s, second at %s",
+ strf("Multiple anchor points defined in blockImage, first point is at {}, second at {}",
*anchorPosition,
pos));
anchorPosition = pos;
diff --git a/source/game/StarWorldTiles.cpp b/source/game/StarWorldTiles.cpp
index 93ada65..218339b 100644
--- a/source/game/StarWorldTiles.cpp
+++ b/source/game/StarWorldTiles.cpp
@@ -66,7 +66,7 @@ void ServerTile::write(DataStream& ds) const {
void ServerTile::read(DataStream& ds, VersionNumber serializationVersion) {
if (serializationVersion < 416 || serializationVersion > CurrentSerializationVersion)
- throw StarException::format("Cannot read ServerTile - serialization version %s incompatible with current version %s\n", serializationVersion, CurrentSerializationVersion);
+ throw StarException::format("Cannot read ServerTile - serialization version {} incompatible with current version {}\n", serializationVersion, CurrentSerializationVersion);
ds.read(foreground);
ds.read(foregroundHueShift);
diff --git a/source/game/interfaces/StarBeamItem.cpp b/source/game/interfaces/StarBeamItem.cpp
index 4a6a98b..66e29c1 100644
--- a/source/game/interfaces/StarBeamItem.cpp
+++ b/source/game/interfaces/StarBeamItem.cpp
@@ -176,7 +176,7 @@ List<Drawable> BeamItem::beamDrawables(bool canPlace) const {
if (!endImage.empty()) {
if (!canPlace) {
ImageOperation op = HueShiftImageOperation::hueShiftDegrees(120);
- endImage = strf("%s?%s", endImage, imageOperationToString(op));
+ endImage = strf("{}?{}", endImage, imageOperationToString(op));
}
Drawable ball = Drawable::makeImage(endImage, 1.0f / TilePixels, true, m_beamCurve.dest());
diff --git a/source/game/items/StarMaterialItem.cpp b/source/game/items/StarMaterialItem.cpp
index 4ba1609..73ef1d1 100644
--- a/source/game/items/StarMaterialItem.cpp
+++ b/source/game/items/StarMaterialItem.cpp
@@ -18,7 +18,7 @@ MaterialItem::MaterialItem(Json const& config, String const& directory, Json con
auto drawables = iconDrawables();
for (auto& d : drawables) {
if (d.isImage()) {
- String image = strf("?hueshift=%s", materialHueToDegrees(m_materialHueShift));
+ String image = strf("?hueshift={}", materialHueToDegrees(m_materialHueShift));
d.imagePart().addDirectives(image, false);
}
}
diff --git a/source/game/items/StarObjectItem.cpp b/source/game/items/StarObjectItem.cpp
index bd4749b..58547fb 100644
--- a/source/game/items/StarObjectItem.cpp
+++ b/source/game/items/StarObjectItem.cpp
@@ -83,7 +83,7 @@ bool ObjectItem::placeInWorld(FireMode, bool shifting) {
}
}
} catch (StarException const& e) {
- Logger::error("Failed to instantiate object for placement. %s %s : %s",
+ Logger::error("Failed to instantiate object for placement. {} {} : {}",
objectName(),
objectParameters().repr(0, true),
outputException(e, true));
diff --git a/source/game/items/StarTools.cpp b/source/game/items/StarTools.cpp
index 6edf3fb..819e87a 100644
--- a/source/game/items/StarTools.cpp
+++ b/source/game/items/StarTools.cpp
@@ -19,7 +19,7 @@ MiningTool::MiningTool(Json const& config, String const& directory, Json const&
m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
m_frameTiming = 0;
for (size_t i = 0; i < (size_t)m_frames; i++)
- m_animationFrame.append(m_image.replace("{frame}", strf("%s", i)));
+ m_animationFrame.append(m_image.replace("{frame}", strf("{}", i)));
m_idleFrame = m_image.replace("{frame}", "idle");
m_handPosition = jsonToVec2F(instanceValue("handPosition"));
m_blockRadius = instanceValue("blockRadius").toFloat();
@@ -154,7 +154,7 @@ HarvestingTool::HarvestingTool(Json const& config, String const& directory, Json
m_frames = instanceValue("frames", 1).toInt();
m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
for (size_t i = 0; i < (size_t)m_frames; i++)
- m_animationFrame.append(m_image.replace("{frame}", strf("%s", i)));
+ m_animationFrame.append(m_image.replace("{frame}", strf("{}", i)));
m_idleFrame = m_image.replace("{frame}", "idle");
m_handPosition = jsonToVec2F(instanceValue("handPosition"));
@@ -494,7 +494,7 @@ TillingTool::TillingTool(Json const& config, String const& directory, Json const
m_frames = instanceValue("frames", 1).toInt();
m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
for (size_t i = 0; i < (size_t)m_frames; i++)
- m_animationFrame.append(m_image.replace("{frame}", strf("%s", i)));
+ m_animationFrame.append(m_image.replace("{frame}", strf("{}", i)));
m_idleFrame = m_image.replace("{frame}", "idle");
m_handPosition = jsonToVec2F(instanceValue("handPosition"));
diff --git a/source/game/items/StarUnlockItem.cpp b/source/game/items/StarUnlockItem.cpp
index face195..471c39c 100644
--- a/source/game/items/StarUnlockItem.cpp
+++ b/source/game/items/StarUnlockItem.cpp
@@ -56,7 +56,7 @@ void UnlockItem::fireTriggered() {
for (Json v : playerConfig.get("defaultBlueprints", JsonObject()).getArray(*m_tierRecipesUnlock, JsonArray()))
blueprints.append(ItemDescriptor(v));
- auto speciesConfig = Root::singleton().assets()->json(strf("/species/%s.species", player->species()));
+ auto speciesConfig = Root::singleton().assets()->json(strf("/species/{}.species", player->species()));
for (Json v : speciesConfig.get("defaultBlueprints", JsonObject()).getArray(*m_tierRecipesUnlock, JsonArray()))
blueprints.append(ItemDescriptor(v));
diff --git a/source/game/objects/StarContainerObject.cpp b/source/game/objects/StarContainerObject.cpp
index ee0505d..399c426 100644
--- a/source/game/objects/StarContainerObject.cpp
+++ b/source/game/objects/StarContainerObject.cpp
@@ -204,7 +204,7 @@ InteractAction ContainerObject::interact(InteractRequest const&) {
}
Json ContainerObject::containerGuiConfig() const {
- return Root::singleton().assets()->json(configValue("uiConfig").toString().replace("<slots>", strf("%s", m_items->size())));
+ return Root::singleton().assets()->json(configValue("uiConfig").toString().replace("<slots>", strf("{}", m_items->size())));
}
String ContainerObject::containerDescription() const {
diff --git a/source/game/scripting/StarLuaComponents.cpp b/source/game/scripting/StarLuaComponents.cpp
index 000e787..2d7c819 100644
--- a/source/game/scripting/StarLuaComponents.cpp
+++ b/source/game/scripting/StarLuaComponents.cpp
@@ -29,7 +29,7 @@ void LuaBaseComponent::setScripts(StringList scripts) {
void LuaBaseComponent::addCallbacks(String groupName, LuaCallbacks callbacks) {
if (!m_callbacks.insert(groupName, callbacks).second)
- throw LuaComponentException::format("Duplicate callbacks named '%s' in LuaBaseComponent", groupName);
+ throw LuaComponentException::format("Duplicate callbacks named '{}' in LuaBaseComponent", groupName);
if (m_context)
m_context->setCallbacks(groupName, callbacks);
@@ -75,7 +75,7 @@ bool LuaBaseComponent::init() {
try {
m_context = m_luaRoot->createContext(m_scripts);
} catch (LuaException const& e) {
- Logger::error("Exception while creating lua context for scripts '%s': %s", m_scripts, outputException(e, true));
+ Logger::error("Exception while creating lua context for scripts '{}': {}", m_scripts, outputException(e, true));
m_error = String(printException(e, false));
m_context.reset();
return false;
@@ -86,7 +86,7 @@ bool LuaBaseComponent::init() {
try {
m_context->invokePath("init");
} catch (LuaException const& e) {
- Logger::error("Exception while calling script init: %s", outputException(e, true));
+ Logger::error("Exception while calling script init: {}", outputException(e, true));
m_error = String(printException(e, false));
m_context.reset();
return false;
@@ -102,7 +102,7 @@ void LuaBaseComponent::uninit() {
try {
m_context->invokePath("uninit");
} catch (LuaException const& e) {
- Logger::error("Exception while calling script uninit: %s", outputException(e, true));
+ Logger::error("Exception while calling script uninit: {}", outputException(e, true));
m_error = String(printException(e, false));
}
}
diff --git a/source/game/scripting/StarLuaComponents.hpp b/source/game/scripting/StarLuaComponents.hpp
index dec2b23..f370679 100644
--- a/source/game/scripting/StarLuaComponents.hpp
+++ b/source/game/scripting/StarLuaComponents.hpp
@@ -184,7 +184,7 @@ Maybe<Ret> LuaBaseComponent::invoke(String const& name, V&&... args) {
return {};
return m_context->luaTo<LuaFunction>(move(method)).invoke<Ret>(forward<V>(args)...);
} catch (LuaException const& e) {
- Logger::error("Exception while invoking lua function '%s'. %s", name, outputException(e, true));
+ Logger::error("Exception while invoking lua function '{}'. {}", name, outputException(e, true));
setError(printException(e, false));
return {};
}
@@ -198,7 +198,7 @@ Maybe<LuaValue> LuaBaseComponent::eval(String const& code) {
try {
return m_context->eval<Ret>(code);
} catch (LuaException const& e) {
- Logger::error("Exception while evaluating lua in context: %s", outputException(e, true));
+ Logger::error("Exception while evaluating lua in context: {}", outputException(e, true));
return {};
}
}
@@ -316,7 +316,7 @@ Maybe<Json> LuaMessageHandlingComponent<Base>::handleMessage(
return handler->template invoke<Json>(message, localMessage, luaUnpack(args));
} catch (LuaException const& e) {
Logger::error(
- "Exception while invoking lua message handler for message '%s'. %s", message, outputException(e, true));
+ "Exception while invoking lua message handler for message '{}'. {}", message, outputException(e, true));
Base::setError(String(printException(e, false)));
}
}
diff --git a/source/game/scripting/StarLuaRoot.cpp b/source/game/scripting/StarLuaRoot.cpp
index 70602de..4d6e8cf 100644
--- a/source/game/scripting/StarLuaRoot.cpp
+++ b/source/game/scripting/StarLuaRoot.cpp
@@ -34,7 +34,7 @@ LuaRoot::~LuaRoot() {
JsonObject profile;
profile.set("function", entry.name.value("<function>"));
profile.set("scope", entry.nameScope.value("?"));
- profile.set("source", strf("%s:%s", entry.source, entry.sourceLine));
+ profile.set("source", strf("{}:{}", entry.source, entry.sourceLine));
profile.set("self", entry.selfTime);
profile.set("total", entry.totalTime);
List<LuaProfileEntry> calls;
@@ -51,9 +51,9 @@ LuaRoot::~LuaRoot() {
File::makeDirectory(m_storageDirectory);
}
- String filename = strf("%s.luaprofile", Time::printCurrentDateAndTime("<year>-<month>-<day>-<hours>-<minutes>-<seconds>-<millis>"));
+ String filename = strf("{}.luaprofile", Time::printCurrentDateAndTime("<year>-<month>-<day>-<hours>-<minutes>-<seconds>-<millis>"));
String path = File::relativeTo(m_storageDirectory, filename);
- Logger::info("Writing lua profile %s", filename);
+ Logger::info("Writing lua profile {}", filename);
File::writeFile(profileSummary, path);
}
}
diff --git a/source/game/scripting/StarWorldLuaBindings.cpp b/source/game/scripting/StarWorldLuaBindings.cpp
index ca0ebb2..9906eec 100644
--- a/source/game/scripting/StarWorldLuaBindings.cpp
+++ b/source/game/scripting/StarWorldLuaBindings.cpp
@@ -175,7 +175,7 @@ namespace LuaBindings {
} else if (*order == "random") {
Random::shuffle(entities);
} else {
- throw StarException(strf("Unsupported query order %s", order->ptr()));
+ throw StarException(strf("Unsupported query order {}", order->ptr()));
}
}
@@ -820,7 +820,7 @@ namespace LuaBindings {
return true;
}
} catch (StarException const& exception) {
- Logger::warn("Could not create placable object of kind '%s', exception caught: %s",
+ Logger::warn("Could not create placable object of kind '{}', exception caught: {}",
objectType,
outputException(exception, false));
}
@@ -860,7 +860,7 @@ namespace LuaBindings {
Logger::warn("Could not spawn item, item empty in WorldCallbacks::spawnItem");
} catch (StarException const& exception) {
- Logger::warn("Could not spawn Item of kind '%s', exception caught: %s", itemType, outputException(exception, false));
+ Logger::warn("Could not spawn Item of kind '{}', exception caught: {}", itemType, outputException(exception, false));
}
return {};
@@ -878,7 +878,7 @@ namespace LuaBindings {
}
} catch (StarException const& exception) {
Logger::warn(
- "Could not spawn treasure from pool '%s', exception caught: %s", pool, outputException(exception, false));
+ "Could not spawn treasure from pool '{}', exception caught: {}", pool, outputException(exception, false));
}
return entities;
}
@@ -904,7 +904,7 @@ namespace LuaBindings {
return monster->inWorld() ? monster->entityId() : Maybe<EntityId>();
} catch (StarException const& exception) {
Logger::warn(
- "Could not spawn Monster of type '%s', exception caught: %s", arg1, outputException(exception, false));
+ "Could not spawn Monster of type '{}', exception caught: {}", arg1, outputException(exception, false));
return {};
}
}
@@ -936,7 +936,7 @@ namespace LuaBindings {
world->addEntity(npc);
return npc->inWorld() ? npc->entityId() : Maybe<EntityId>();
} catch (StarException const& exception) {
- Logger::warn("Could not spawn NPC of species '%s' and type '%s', exception caught: %s",
+ Logger::warn("Could not spawn NPC of species '{}' and type '{}', exception caught: {}",
arg2,
typeName,
outputException(exception, false));
@@ -954,7 +954,7 @@ namespace LuaBindings {
return stagehand->inWorld() ? stagehand->entityId() : Maybe<EntityId>();
} catch (StarException const& exception) {
Logger::warn(
- "Could not spawn Stagehand of type '%s', exception caught: %s", typeName, outputException(exception, false));
+ "Could not spawn Stagehand of type '{}', exception caught: {}", typeName, outputException(exception, false));
return {};
}
}
@@ -977,7 +977,7 @@ namespace LuaBindings {
return projectile->inWorld() ? projectile->entityId() : Maybe<EntityId>();
} catch (StarException const& exception) {
Logger::warn(
- "Could not spawn Projectile of type '%s', exception caught: %s", projectileType, outputException(exception, false));
+ "Could not spawn Projectile of type '{}', exception caught: {}", projectileType, outputException(exception, false));
return {};
}
}
@@ -1122,9 +1122,9 @@ namespace LuaBindings {
else if (auto stagehand = as<Stagehand>(entity.get()))
stagehand->setUniqueId(uniqueId);
else if (entity)
- throw StarException::format("Cannot set unique id on entity of type %s", EntityTypeNames.getRight(entity->entityType()));
+ throw StarException::format("Cannot set unique id on entity of type {}", EntityTypeNames.getRight(entity->entityType()));
else
- throw StarException::format("No such entity with id %s", entityId);
+ throw StarException::format("No such entity with id {}", entityId);
}
Json ServerWorldCallbacks::takeItemDrop(World* world, EntityId entityId, Maybe<EntityId> const& takenBy) {
@@ -1169,7 +1169,7 @@ namespace LuaBindings {
void WorldDebugCallbacks::debugText(LuaEngine& engine, LuaVariadic<LuaValue> const& args) {
if (args.size() < 3)
- throw StarException(strf("Too few arguments to debugText: %s", args.size()));
+ throw StarException(strf("Too few arguments to debugText: {}", args.size()));
Vec2F const position = engine.luaTo<Vec2F>(args.at(args.size() - 2));
Vec4B const color = engine.luaTo<Color>(args.at(args.size() - 1)).toRgba();
@@ -1228,7 +1228,7 @@ namespace LuaBindings {
else if (orientationName.empty())
orientation = LoungeOrientation::None;
else
- throw StarException(strf("Unsupported loungeableQuery orientation %s", orientationName));
+ throw StarException(strf("Unsupported loungeableQuery orientation {}", orientationName));
auto filter = [orientation](shared_ptr<LoungeableObject> const& entity) -> bool {
auto loungeable = as<LoungeableEntity>(entity);
@@ -1419,7 +1419,7 @@ namespace LuaBindings {
} else if (handName == "alt") {
toolHand = ToolHand::Alt;
} else {
- throw StarException(strf("Unknown tool hand %s", handName));
+ throw StarException(strf("Unknown tool hand {}", handName));
}
if (auto entity = world->get<ToolUserEntity>(entityId)) {
@@ -1438,7 +1438,7 @@ namespace LuaBindings {
} else if (handName == "alt") {
toolHand = ToolHand::Alt;
} else {
- throw StarException(strf("Unknown tool hand %s", handName));
+ throw StarException(strf("Unknown tool hand {}", handName));
}
if (auto entity = world->get<ToolUserEntity>(entityId)) {
@@ -1713,7 +1713,7 @@ namespace LuaBindings {
Maybe<LuaValue> WorldEntityCallbacks::callScriptedEntity(World* world, EntityId entityId, String const& function, LuaVariadic<LuaValue> const& args) {
auto entity = as<ScriptedEntity>(world->entity(entityId));
if (!entity || !entity->isMaster())
- throw StarException::format("Entity %s does not exist or is not a local master scripted entity", entityId);
+ throw StarException::format("Entity {} does not exist or is not a local master scripted entity", entityId);
return entity->callScript(function, args);
}
@@ -1794,7 +1794,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported material layer %s", layerName));
+ throw StarException(strf("Unsupported material layer {}", layerName));
}
auto materialId = world->material(Vec2I::floor(position), layer);
@@ -1815,7 +1815,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported mod layer %s", layerName));
+ throw StarException(strf("Unsupported mod layer {}", layerName));
}
auto modId = world->mod(Vec2I::floor(position), layer);
@@ -1834,7 +1834,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported material layer %s", layerName));
+ throw StarException(strf("Unsupported material layer {}", layerName));
}
return world->materialHueShift(Vec2I::floor(position), layer);
@@ -1847,7 +1847,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported material layer %s", layerName));
+ throw StarException(strf("Unsupported material layer {}", layerName));
}
return world->modHueShift(Vec2I::floor(position), layer);
@@ -1860,7 +1860,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported material layer %s", layerName));
+ throw StarException(strf("Unsupported material layer {}", layerName));
}
return world->colorVariant(Vec2I::floor(position), layer);
@@ -1873,7 +1873,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported material layer %s", layerName));
+ throw StarException(strf("Unsupported material layer {}", layerName));
}
world->modifyTile(Vec2I::floor(position), PlaceMaterialColor{layer, color}, true);
@@ -1896,7 +1896,7 @@ namespace LuaBindings {
} else if (layerName == "background") {
layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported damageTile layer %s", layerName));
+ throw StarException(strf("Unsupported damageTile layer {}", layerName));
}
unsigned harvestLevel = 999;
@@ -1932,13 +1932,13 @@ namespace LuaBindings {
} else if (layerName == "background") {
placeMaterial.layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported damageTile layer %s", layerName));
+ throw StarException(strf("Unsupported damageTile layer {}", layerName));
}
auto materialName = arg3;
auto materialDatabase = Root::singleton().materialDatabase();
if (!materialDatabase->materialNames().contains(materialName))
- throw StarException(strf("Unknown material name %s", materialName));
+ throw StarException(strf("Unknown material name {}", materialName));
placeMaterial.material = materialDatabase->materialId(materialName);
if (arg4)
@@ -1960,13 +1960,13 @@ namespace LuaBindings {
} else if (layerName == "background") {
placeMod.layer = TileLayer::Background;
} else {
- throw StarException(strf("Unsupported damageTile layer %s", layerName));
+ throw StarException(strf("Unsupported damageTile layer {}", layerName));
}
auto modName = arg3;
auto materialDatabase = Root::singleton().materialDatabase();
if (!materialDatabase->modNames().contains(modName))
- throw StarException(strf("Unknown mod name %s", modName));
+ throw StarException(strf("Unknown mod name {}", modName));
placeMod.mod = materialDatabase->modId(modName);
if (arg4)
diff --git a/source/json_tool/editor_gui.cpp b/source/json_tool/editor_gui.cpp
index d533392..5b52e55 100644
--- a/source/json_tool/editor_gui.cpp
+++ b/source/json_tool/editor_gui.cpp
@@ -117,7 +117,7 @@ void JsonEditor::displayCurrentFile() {
String file = m_files.get(m_fileIndex);
size_t progress = (m_fileIndex + 1) * 100 / m_files.size();
- String status = strf("Editing file %s/%s (%s%%): %s", m_fileIndex + 1, m_files.size(), progress, file);
+ String status = strf("Editing file {}/{} ({}%): {}", m_fileIndex + 1, m_files.size(), progress, file);
m_statusLabel->setText(status.utf8Ptr());
m_backButton->setEnabled(m_fileIndex != 0);
diff --git a/source/json_tool/json_tool.cpp b/source/json_tool/json_tool.cpp
index 13c2200..4ea5b05 100644
--- a/source/json_tool/json_tool.cpp
+++ b/source/json_tool/json_tool.cpp
@@ -53,12 +53,12 @@ String Star::reprWithLineEnding(FormattedJson const& json) {
// unix.
String repr = json.repr();
if (repr.contains("\r"))
- return strf("%s\r\n", repr);
- return strf("%s\n", repr);
+ return strf("{}\r\n", repr);
+ return strf("{}\n", repr);
}
void OutputOnSeparateLines::out(FormattedJson const& json) {
- coutf("%s", reprWithLineEnding(json));
+ coutf("{}", reprWithLineEnding(json));
}
void OutputOnSeparateLines::flush() {}
@@ -73,7 +73,7 @@ void ArrayOutput::flush() {
for (FormattedJson const& result : m_results) {
array = array.append(result);
}
- coutf("%s", reprWithLineEnding(array));
+ coutf("{}", reprWithLineEnding(array));
}
FormattedJson Star::addOrSet(bool add,
@@ -140,7 +140,7 @@ void forEachChild(FormattedJson const& parent, function<void(FormattedJson const
}
} else {
throw JsonPath::TraversalException::format(
- "Cannot get the children of Json type %s, must be either Array or Object", parent.typeName());
+ "Cannot get the children of Json type {}, must be either Array or Object", parent.typeName());
}
}
@@ -354,7 +354,7 @@ Maybe<ParsedArgs> parseArgs(int argc, char** argv) {
} else {
if (!File::exists(arg)) {
- cerrf("File %s doesn't exist\n", arg);
+ cerrf("File {} doesn't exist\n", arg);
return {};
}
parsed.inputs.append(FileInput{arg});
@@ -415,23 +415,23 @@ int main(int argc, char** argv) {
Maybe<ParsedArgs> parsedArgs = parseArgs(argc, argv);
if (!parsedArgs) {
- cerrf("Usage: %s [--get <json-path>] (-j <json> | <json-file>*)\n", argv[0]);
+ cerrf("Usage: {} [--get <json-path>] (-j <json> | <json-file>*)\n", argv[0]);
cerrf(
- "Usage: %s --set <json-path> <json> [-i] [(--at (beginning|end) | --before <key> | --after <key>)] (-j "
+ "Usage: {} --set <json-path> <json> [-i] [(--at (beginning|end) | --before <key> | --after <key>)] (-j "
"<json> | <json-file>*)\n",
argv[0]);
cerrf(
- "Usage: %s --add <json-path> <json> [-i] [(--at (beginning|end) | --before <key> | --after <key>)] (-j "
+ "Usage: {} --add <json-path> <json> [-i] [(--at (beginning|end) | --before <key> | --after <key>)] (-j "
"<json> | <json-file>*)\n",
argv[0]);
cerrf(
- "Usage: %s --edit <json-path> [(--at (beginning|end) | --before <key> | --after <key>)] [--input "
+ "Usage: {} --edit <json-path> [(--at (beginning|end) | --before <key> | --after <key>)] [--input "
"(csv|json|string)] <json-file>+\n",
argv[0]);
cerrf("\n");
- cerrf("Example: %s --get /dialog/0/message guard.npctype\n", argv[0]);
- cerrf("Example: %s --get 'foo[0]' -j '{\"foo\":[0,1,2,3]}'\n", argv[0]);
- cerrf("Example: %s --edit /tags --input csv --find ../assets/ .object\n", argv[0]);
+ cerrf("Example: {} --get /dialog/0/message guard.npctype\n", argv[0]);
+ cerrf("Example: {} --get 'foo[0]' -j '{\"foo\":[0,1,2,3]}'\n", argv[0]);
+ cerrf("Example: {} --edit /tags --input csv --find ../assets/ .object\n", argv[0]);
return 1;
}
@@ -457,15 +457,15 @@ int main(int argc, char** argv) {
return 0;
} catch (JsonParsingException const& e) {
- cerrf("%s\n", e.what());
+ cerrf("{}\n", e.what());
return 1;
} catch (JsonException const& e) {
- cerrf("%s\n", e.what());
+ cerrf("{}\n", e.what());
return 1;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/mod_uploader/StarModUploader.cpp b/source/mod_uploader/StarModUploader.cpp
index c8c86e6..a2d0d20 100644
--- a/source/mod_uploader/StarModUploader.cpp
+++ b/source/mod_uploader/StarModUploader.cpp
@@ -183,7 +183,7 @@ void ModUploader::loadDirectory() {
}
String modId = metadata.value("steamContentId", "").toString();
- m_modIdLabel->setText(toQString(strf("<a href=\"steam://url/CommunityFilePage/%s\">%s</a>", modId, modId)));
+ m_modIdLabel->setText(toQString(strf("<a href=\"steam://url/CommunityFilePage/{}\">{}</a>", modId, modId)));
String previewFile = File::relativeTo(*m_modDirectory, "_previewimage");
if (File::isFile(previewFile)) {
@@ -303,23 +303,23 @@ void ModUploader::uploadToSteam() {
}
if (m_steamItemCreateResult->first.m_eResult != k_EResultOK) {
- QMessageBox::critical(this, "Error", strf("Error creating new Steam UGC Item (%s)", m_steamItemCreateResult->first.m_eResult).c_str());
+ QMessageBox::critical(this, "Error", strf("Error creating new Steam UGC Item ({})", m_steamItemCreateResult->first.m_eResult).c_str());
return;
}
modIdString = toString(m_steamItemCreateResult->first.m_nPublishedFileId);
- String modUrl = strf("steam://url/CommunityFilePage/%s", modIdString);
+ String modUrl = strf("steam://url/CommunityFilePage/{}", modIdString);
metadata.set("steamContentId", modIdString);
metadata.set("link", modUrl);
m_assetSource->setMetadata(metadata);
- m_modIdLabel->setText(toQString(strf("<a href=\"%s\">%s</a>", modUrl, modIdString)));
+ m_modIdLabel->setText(toQString(strf("<a href=\"{}\">{}</a>", modUrl, modIdString)));
}
String steamUploadDir = File::temporaryDirectory();
auto progressCallback = [&progress](size_t i, size_t total, String, String assetPath) {
- progress.setLabelText(toQString(strf("Packing '%s'", assetPath)));
+ progress.setLabelText(toQString(strf("Packing '{}'", assetPath)));
progress.setMaximum(total);
progress.setValue(i);
QApplication::processEvents();
@@ -378,7 +378,7 @@ void ModUploader::uploadToSteam() {
}
if (m_steamItemSubmitResult->first.m_eResult != k_EResultOK) {
- QMessageBox::critical(this, "Error", strf("Error submitting changes to the Steam UGC item (%s)", m_steamItemSubmitResult->first.m_eResult).c_str());
+ QMessageBox::critical(this, "Error", strf("Error submitting changes to the Steam UGC item ({})", m_steamItemSubmitResult->first.m_eResult).c_str());
return;
}
}
diff --git a/source/mod_uploader/main.cpp b/source/mod_uploader/main.cpp
index 978039a..ce75698 100644
--- a/source/mod_uploader/main.cpp
+++ b/source/mod_uploader/main.cpp
@@ -22,8 +22,8 @@ int main(int argc, char** argv) {
try {
return app.exec();
} catch (std::exception const& e) {
- QMessageBox::critical(nullptr, "Error", toQString(strf("Exception caught: %s\n", outputException(e, true))));
- coutf("Exception caught: %s\n", outputException(e, true));
+ QMessageBox::critical(nullptr, "Error", toQString(strf("Exception caught: {}\n", outputException(e, true))));
+ coutf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/rendering/StarTextPainter.cpp b/source/rendering/StarTextPainter.cpp
index 5de04ac..6db4a34 100644
--- a/source/rendering/StarTextPainter.cpp
+++ b/source/rendering/StarTextPainter.cpp
@@ -7,7 +7,7 @@ namespace Star {
namespace Text {
String stripEscapeCodes(String const& s) {
- String regex = strf("\\%s[^;]*%s", CmdEsc, EndEsc);
+ String regex = strf("\\{}[^;]*{}", CmdEsc, EndEsc);
return std::regex_replace(s.utf8(), std::regex(regex.utf8()), "");
}
diff --git a/source/rendering/StarTilePainter.cpp b/source/rendering/StarTilePainter.cpp
index dce4fac..68e1110 100644
--- a/source/rendering/StarTilePainter.cpp
+++ b/source/rendering/StarTilePainter.cpp
@@ -310,7 +310,7 @@ bool TilePainter::produceTerrainPrimitives(HashMap<QuadZLevel, List<RenderPrimit
if (hue == 0)
texture = piece->texture;
else
- texture = strf("%s?hueshift=%s", piece->texture, materialHueToDegrees(hue));
+ texture = strf("{}?hueshift={}", piece->texture, materialHueToDegrees(hue));
return m_textureGroup->create(*assets->image(texture));
});
diff --git a/source/server/StarServerQueryThread.cpp b/source/server/StarServerQueryThread.cpp
index 446ecbb..2011f42 100644
--- a/source/server/StarServerQueryThread.cpp
+++ b/source/server/StarServerQueryThread.cpp
@@ -220,7 +220,7 @@ void ServerQueryThread::run() {
processPacket(udpAddress, udpData, len);
} catch (SocketClosedException const&) {
} catch (std::exception const& e) {
- Logger::error("ServerQueryThread exception caught: %s", outputException(e, true));
+ Logger::error("ServerQueryThread exception caught: {}", outputException(e, true));
}
}
}
diff --git a/source/server/StarServerRconClient.cpp b/source/server/StarServerRconClient.cpp
index a42a8ea..91e651b 100644
--- a/source/server/StarServerRconClient.cpp
+++ b/source/server/StarServerRconClient.cpp
@@ -36,12 +36,12 @@ String ServerRconClient::handleCommand(String commandLine) {
return commandLine;
} else if (command == "broadcast" || command == "say") {
m_universe->adminBroadcast(commandLine);
- return strf("OK: said %s", commandLine);
+ return strf("OK: said {}", commandLine);
} else if (command == "stop") {
m_universe->stop();
return "OK: shutting down";
} else {
- return m_universe->adminCommand(strf("%s %s", command, commandLine));
+ return m_universe->adminCommand(strf("{} {}", command, commandLine));
}
}
@@ -118,17 +118,17 @@ void ServerRconClient::processRequest() {
String command;
m_packetBuffer >> command;
try {
- Logger::info("RCON %s: %s", m_socket->remoteAddress(), command);
+ Logger::info("RCON {}: {}", m_socket->remoteAddress(), command);
sendCmdResponse(requestId, handleCommand(command));
} catch (std::exception const& e) {
- sendCmdResponse(requestId, strf("RCON: Error executing: %s: %s", command, outputException(e, true)));
+ sendCmdResponse(requestId, strf("RCON: Error executing: {}: {}", command, outputException(e, true)));
}
} else {
sendAuthFailure();
}
break;
default:
- sendCmdResponse(requestId, strf("Unknown request %06x", cmd));
+ sendCmdResponse(requestId, strf("Unknown request {:06x}", cmd));
}
}
@@ -138,7 +138,7 @@ void ServerRconClient::run() {
processRequest();
} catch (NoMoreRequests const&) {
} catch (std::exception const& e) {
- Logger::error("ServerRconClient exception caught: %s", outputException(e, false));
+ Logger::error("ServerRconClient exception caught: {}", outputException(e, false));
}
}
diff --git a/source/server/StarServerRconThread.cpp b/source/server/StarServerRconThread.cpp
index 45f94b3..a9842ee 100644
--- a/source/server/StarServerRconThread.cpp
+++ b/source/server/StarServerRconThread.cpp
@@ -55,7 +55,7 @@ void ServerRconThread::run() {
}
}
} catch (std::exception const& e) {
- Logger::error("ServerRconThread exception caught: %s", e.what());
+ Logger::error("ServerRconThread exception caught: {}", e.what());
}
}
diff --git a/source/server/main.cpp b/source/server/main.cpp
index 6522acf..8d734e0 100644
--- a/source/server/main.cpp
+++ b/source/server/main.cpp
@@ -45,7 +45,7 @@ int main(int argc, char** argv) {
auto configuration = root->configuration();
{
- Logger::info("Server Version %s (%s) Source ID: %s Protocol: %s", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion);
+ Logger::info("Server Version {} ({}) Source ID: {} Protocol: {}", StarVersionString, StarArchitectureString, StarSourceIdentifierString, StarProtocolVersion);
UniverseServerUPtr server = make_unique<UniverseServer>(root->toStoragePath("universe"));
server->setListeningTcp(true);
diff --git a/source/test/spawn_test.cpp b/source/test/spawn_test.cpp
index 250dc22..202cc55 100644
--- a/source/test/spawn_test.cpp
+++ b/source/test/spawn_test.cpp
@@ -12,7 +12,7 @@ void validateWorld(TestUniverse& testUniverse) {
// Just make sure the test world draws something for now, this will grow to
// include more than this.
- EXPECT_GE(testUniverse.currentClientDrawables().size(), 1u) << strf("world: %s", testUniverse.currentPlayerWorld());
+ EXPECT_GE(testUniverse.currentClientDrawables().size(), 1u) << strf("world: {}", testUniverse.currentPlayerWorld());
auto assets = Root::singleton().assets();
for (auto const& drawable : testUniverse.currentClientDrawables()) {
diff --git a/source/test/string_test.cpp b/source/test/string_test.cpp
index ed01a4f..dcb2441 100644
--- a/source/test/string_test.cpp
+++ b/source/test/string_test.cpp
@@ -112,8 +112,8 @@ TEST(StringTest, contains) {
}
TEST(StringTest, format) {
- EXPECT_EQ(strf("(%s, %s, %s)", 1, "foo", 3.2), "(1, foo, 3.2)");
- EXPECT_EQ(strf("%s (%s, %s, %s)", String("asdf\0", 5), 1, "foo", 3.2), String("asdf\0 (1, foo, 3.2)", 19));
+ EXPECT_EQ(strf("({}, {}, {})", 1, "foo", 3.2), "(1, foo, 3.2)");
+ EXPECT_EQ(strf("{} ({}, {}, {})", String("asdf\0", 5), 1, "foo", 3.2), String("asdf\0 (1, foo, 3.2)", 19));
}
TEST(StringTest, append) {
diff --git a/source/utility/asset_packer.cpp b/source/utility/asset_packer.cpp
index 7777264..7caf0aa 100644
--- a/source/utility/asset_packer.cpp
+++ b/source/utility/asset_packer.cpp
@@ -31,8 +31,8 @@ int main(int argc, char** argv) {
try {
configFileContents = File::readFileString(configFile);
} catch (IOException const& e) {
- cerrf("Could not open specified configFile: %s\n", configFile);
- cerrf("For the following reason: %s\n", outputException(e, false));
+ cerrf("Could not open specified configFile: {}\n", configFile);
+ cerrf("For the following reason: {}\n", outputException(e, false));
return 1;
}
@@ -40,8 +40,8 @@ int main(int argc, char** argv) {
try {
configFileJson = Json::parseJson(configFileContents);
} catch (JsonParsingException const& e) {
- cerrf("Could not parse the specified configFile: %s\n", configFile);
- cerrf("For the following reason: %s\n", outputException(e, false));
+ cerrf("Could not parse the specified configFile: {}\n", configFile);
+ cerrf("For the following reason: {}\n", outputException(e, false));
return 1;
}
@@ -51,8 +51,8 @@ int main(int argc, char** argv) {
ignoreFiles.appendAll(jsonToStringList(configFileJson.get("serverIgnore", JsonArray())));
extensionOrdering = jsonToStringList(configFileJson.get("extensionOrdering", JsonArray()));
} catch (JsonException const& e) {
- cerrf("Could not read the asset_packer config file %s\n", configFile);
- cerrf("%s\n", outputException(e, false));
+ cerrf("Could not read the asset_packer config file {}\n", configFile);
+ cerrf("{}\n", outputException(e, false));
return 1;
}
}
@@ -62,18 +62,18 @@ int main(int argc, char** argv) {
function<void(size_t, size_t, String, String, bool)> BuildProgressCallback;
auto progressCallback = [verbose](size_t, size_t, String filePath, String assetPath) {
if (verbose)
- coutf("Adding file '%s' to the target pak as '%s'\n", filePath, assetPath);
+ coutf("Adding file '{}' to the target pak as '{}'\n", filePath, assetPath);
};
outputFilename = File::relativeTo(File::fullPath(File::dirName(outputFilename)), File::baseName(outputFilename));
DirectoryAssetSource directorySource(assetsFolderPath, ignoreFiles);
PackedAssetSource::build(directorySource, outputFilename, extensionOrdering, progressCallback);
- coutf("Output packed assets to %s in %ss\n", outputFilename, Time::monotonicTime() - startTime);
+ coutf("Output packed assets to {} in {}s\n", outputFilename, Time::monotonicTime() - startTime);
return 0;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/asset_unpacker.cpp b/source/utility/asset_unpacker.cpp
index d4d4f6d..487d0b7 100644
--- a/source/utility/asset_unpacker.cpp
+++ b/source/utility/asset_unpacker.cpp
@@ -10,7 +10,7 @@ int main(int argc, char** argv) {
double startTime = Time::monotonicTime();
if (argc != 3) {
- cerrf("Usage: %s <assets pak path> <target output directory>\n", argv[0]);
+ cerrf("Usage: {} <assets pak path> <target output directory>\n", argv[0]);
cerrf("If the target output directory does not exist it will be created\n");
return 1;
}
@@ -35,8 +35,8 @@ int main(int argc, char** argv) {
File::makeDirectoryRecursive(relativeDir);
File::writeFile(fileData, relativePath);
} catch (AssetSourceException const& e) {
- cerrf("Could not open file: %s\n", file);
- cerrf("Reason: %s\n", outputException(e, false));
+ cerrf("Could not open file: {}\n", file);
+ cerrf("Reason: {}\n", outputException(e, false));
}
}
@@ -44,10 +44,10 @@ int main(int argc, char** argv) {
if (!metadata.empty())
File::writeFile(Json(move(metadata)).printJson(2), "_metadata");
- coutf("Unpacked assets to %s in %ss\n", outputFolderPath, Time::monotonicTime() - startTime);
+ coutf("Unpacked assets to {} in {}s\n", outputFolderPath, Time::monotonicTime() - startTime);
return 0;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/dump_versioned_json.cpp b/source/utility/dump_versioned_json.cpp
index 2672548..24ef482 100644
--- a/source/utility/dump_versioned_json.cpp
+++ b/source/utility/dump_versioned_json.cpp
@@ -6,7 +6,7 @@ using namespace Star;
int main(int argc, char** argv) {
try {
if (argc != 3) {
- coutf("Usage, %s <versioned_json_binary> <versioned_json_json>\n", argv[0]);
+ coutf("Usage, {} <versioned_json_binary> <versioned_json_json>\n", argv[0]);
return -1;
}
@@ -14,7 +14,7 @@ int main(int argc, char** argv) {
File::writeFile(versionedJson.toJson().printJson(2), argv[2]);
return 0;
} catch (std::exception const& e) {
- coutf("Error! Caught exception %s\n", outputException(e, true));
+ coutf("Error! Caught exception {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/dungeon_generation_benchmark.cpp b/source/utility/dungeon_generation_benchmark.cpp
index a67cb02..70cbe9e 100644
--- a/source/utility/dungeon_generation_benchmark.cpp
+++ b/source/utility/dungeon_generation_benchmark.cpp
@@ -12,9 +12,9 @@ int main(int argc, char** argv) {
String dungeonWorldName = "outpost";
RootLoader rootLoader({{}, {}, {}, LogLevel::Error, false, {}});
- rootLoader.addParameter("dungeonWorld", "dungeonWorld", OptionParser::Optional, strf("dungeonWorld to test, default is %s", dungeonWorldName));
- rootLoader.addParameter("repetitions", "repetitions", OptionParser::Optional, strf("number of times to generate, default %s", repetitions));
- rootLoader.addParameter("reportevery", "report repetitions", OptionParser::Optional, strf("number of repetitions before each progress report, default %s", reportEvery));
+ rootLoader.addParameter("dungeonWorld", "dungeonWorld", OptionParser::Optional, strf("dungeonWorld to test, default is {}", dungeonWorldName));
+ rootLoader.addParameter("repetitions", "repetitions", OptionParser::Optional, strf("number of times to generate, default {}", repetitions));
+ rootLoader.addParameter("reportevery", "report repetitions", OptionParser::Optional, strf("number of repetitions before each progress report, default {}", reportEvery));
RootUPtr root;
OptionParser::Options options;
@@ -36,13 +36,13 @@ int main(int argc, char** argv) {
double start = Time::monotonicTime();
double lastReport = Time::monotonicTime();
- coutf("testing %s generations of dungeonWorld %s\n", repetitions, dungeonWorldName);
+ coutf("testing {} generations of dungeonWorld {}\n", repetitions, dungeonWorldName);
for (unsigned i = 0; i < repetitions; ++i) {
if (i > 0 && i % reportEvery == 0) {
float gps = reportEvery / (Time::monotonicTime() - lastReport);
lastReport = Time::monotonicTime();
- coutf("[%s] %ss | Generations Per Second: %s\n", i, Time::monotonicTime() - start, gps);
+ coutf("[{}] {}s | Generations Per Second: {}\n", i, Time::monotonicTime() - start, gps);
}
VisitableWorldParametersPtr worldParameters = generateFloatingDungeonWorldParameters(dungeonWorldName);
@@ -50,12 +50,12 @@ int main(int argc, char** argv) {
WorldServer worldServer(move(worldTemplate), File::ephemeralFile());
}
- coutf("Finished %s generations of dungeonWorld %s in %s seconds", repetitions, dungeonWorldName, Time::monotonicTime() - start);
+ coutf("Finished {} generations of dungeonWorld {} in {} seconds", repetitions, dungeonWorldName, Time::monotonicTime() - start);
return 0;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/fix_embedded_tilesets.cpp b/source/utility/fix_embedded_tilesets.cpp
index 262426d..8f49db7 100644
--- a/source/utility/fix_embedded_tilesets.cpp
+++ b/source/utility/fix_embedded_tilesets.cpp
@@ -38,7 +38,7 @@ Maybe<Json> repairTileset(Json tileset, String const& mapPath, String const& til
String tilesetName = tileset.getString("name");
String tilesetFileName = File::relativeTo(tilesetPath, tilesetName + ".json");
if (!File::exists(tilesetFileName))
- throw StarException::format("Tileset %s does not exist. Can't repair %s", tilesetFileName, mapPath);
+ throw StarException::format("Tileset {} does not exist. Can't repair {}", tilesetFileName, mapPath);
return {JsonObject{{"firstgid", firstGid}, {"source", createRelativePath(mapPath, tilesetFileName)}}};
}
@@ -71,7 +71,7 @@ void fixEmbeddedTilesets(String const& searchRoot, String const& tilesetPath) {
if (json.contains("tilesets")) {
if (Maybe<Json> fixed = repair(json, path, tilesetPath)) {
File::writeFile(fixed->repr(2, true), path);
- Logger::info("Repaired %s", path);
+ Logger::info("Repaired {}", path);
}
}
});
@@ -95,7 +95,7 @@ int main(int argc, char* argv[]) {
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/game_repl.cpp b/source/utility/game_repl.cpp
index e52fb07..3ffc300 100644
--- a/source/utility/game_repl.cpp
+++ b/source/utility/game_repl.cpp
@@ -40,12 +40,12 @@ int main(int argc, char** argv) {
try {
auto result = context.eval<LuaVariadic<LuaValue>>(code);
for (auto r : result)
- coutf("%s\n", r);
+ coutf("{}\n", r);
continuation = false;
} catch (LuaIncompleteStatementException const&) {
continuation = true;
} catch (std::exception const& e) {
- coutf("Error: %s\n", outputException(e, false));
+ coutf("Error: {}\n", outputException(e, false));
continuation = false;
}
}
diff --git a/source/utility/generation_benchmark.cpp b/source/utility/generation_benchmark.cpp
index f3f2f97..8e1631c 100644
--- a/source/utility/generation_benchmark.cpp
+++ b/source/utility/generation_benchmark.cpp
@@ -44,7 +44,7 @@ int main(int argc, char** argv) {
if (auto reportEveryOption = options.parameters.maybe("reportevery"))
reportEvery = lexicalCast<unsigned>(reportEveryOption->first());
- coutf("testing generation on coordinate %s\n", coordinate);
+ coutf("testing generation on coordinate {}\n", coordinate);
auto worldParameters = celestialDatabase.parameters(coordinate).take();
auto worldTemplate = make_shared<WorldTemplate>(worldParameters.visitableParameters(), SkyParameters(), worldParameters.seed());
@@ -57,25 +57,25 @@ int main(int argc, char** argv) {
double start = Time::monotonicTime();
double lastReport = Time::monotonicTime();
- coutf("Starting world generation for %s regions\n", regionsToGenerate);
+ coutf("Starting world generation for {} regions\n", regionsToGenerate);
for (unsigned i = 0; i < regionsToGenerate; ++i) {
if (i != 0 && i % reportEvery == 0) {
float gps = reportEvery / (Time::monotonicTime() - lastReport);
lastReport = Time::monotonicTime();
- coutf("[%s] %ss | Generatons Per Second: %s\n", i, Time::monotonicTime() - start, gps);
+ coutf("[{}] {}s | Generatons Per Second: {}\n", i, Time::monotonicTime() - start, gps);
}
RectI region = RectI::withCenter(Vec2I(rand.randInt(0, worldSize[0]), rand.randInt(0, worldSize[1])), Vec2I::filled(regionSize));
worldServer.generateRegion(region);
}
- coutf("Finished generating %s regions with size %sx%s in world '%s' in %s seconds", regionsToGenerate, regionSize, regionSize, coordinate, Time::monotonicTime() - start);
+ coutf("Finished generating {} regions with size {}x{} in world '{}' in {} seconds", regionsToGenerate, regionSize, regionSize, coordinate, Time::monotonicTime() - start);
return 0;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/make_versioned_json.cpp b/source/utility/make_versioned_json.cpp
index 560f532..478e7f6 100644
--- a/source/utility/make_versioned_json.cpp
+++ b/source/utility/make_versioned_json.cpp
@@ -6,7 +6,7 @@ using namespace Star;
int main(int argc, char** argv) {
try {
if (argc != 3) {
- coutf("Usage, %s <versioned_json_json> <versioned_json_binary>\n", argv[0]);
+ coutf("Usage, {} <versioned_json_json> <versioned_json_binary>\n", argv[0]);
return -1;
}
@@ -14,7 +14,7 @@ int main(int argc, char** argv) {
VersionedJson::writeFile(versionedJson, argv[2]);
return 0;
} catch (std::exception const& e) {
- coutf("Error! Caught exception %s\n", outputException(e, true));
+ coutf("Error! Caught exception {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/map_grep.cpp b/source/utility/map_grep.cpp
index 03083e0..9f8bb00 100644
--- a/source/utility/map_grep.cpp
+++ b/source/utility/map_grep.cpp
@@ -57,12 +57,12 @@ void grepMap(SearchParameters const& search, String file) {
for (auto tileLayer : map->tileLayers())
grepTileLayer(search, map, tileLayer, [&](String const& tileName, Vec2I const& pos) {
- coutf("%s: %s: %s @ %s\n", file, tileLayer->name(), tileName, pos);
+ coutf("{}: {}: {} @ {}\n", file, tileLayer->name(), tileName, pos);
});
for (auto objectGroup : map->objectGroups())
grepObjectGroup(search, objectGroup, [&](String const& tileName, Vec2I const& pos) {
- coutf("%s: %s: %s @ %s\n", file, objectGroup->name(), tileName, pos);
+ coutf("{}: {}: {} @ {}\n", file, objectGroup->name(), tileName, pos);
});
}
@@ -110,7 +110,7 @@ int main(int argc, char* argv[]) {
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/planet_mapgen.cpp b/source/utility/planet_mapgen.cpp
index 7bc9f8d..327c7a8 100644
--- a/source/utility/planet_mapgen.cpp
+++ b/source/utility/planet_mapgen.cpp
@@ -38,7 +38,7 @@ int main(int argc, char** argv) {
if (!coordinate)
throw StarException("Could not find world to generate, try again");
- coutf("Generating world with coordinate %s\n", *coordinate);
+ coutf("Generating world with coordinate {}\n", *coordinate);
WorldTemplate worldTemplate(*coordinate, celestialDatabase);
auto size = worldTemplate.size();
@@ -51,7 +51,7 @@ int main(int argc, char** argv) {
size[0] = 1000;
}
- coutf("Generating %s size image for world of type '%s'\n", size, worldTemplate.worldParameters()->typeName);
+ coutf("Generating {} size image for world of type '{}'\n", size, worldTemplate.worldParameters()->typeName);
auto outputImage = make_shared<Image>(size, PixelFormat::RGB24);
Color groundColor = Color::rgb(255, 0, 0);
@@ -111,7 +111,7 @@ int main(int argc, char** argv) {
outputImage->writePng(File::open("mapgen.png", IOMode::Write));
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/render_terrain_selector.cpp b/source/utility/render_terrain_selector.cpp
index a9e508a..570f6c0 100644
--- a/source/utility/render_terrain_selector.cpp
+++ b/source/utility/render_terrain_selector.cpp
@@ -67,7 +67,7 @@ int main(int argc, char** argv) {
}
}
- coutf("Generating %s size image for selector with scale %s\n", size, scale);
+ coutf("Generating {} size image for selector with scale {}\n", size, scale);
auto outputImage = make_shared<Image>(size, PixelFormat::RGB24);
for (size_t x = 0; x < size[0]; ++x) {
@@ -90,7 +90,7 @@ int main(int argc, char** argv) {
outputImage->writePng(File::open("terrain.png", IOMode::Write));
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/tileset_updater.cpp b/source/utility/tileset_updater.cpp
index e94ac53..9c3e252 100644
--- a/source/utility/tileset_updater.cpp
+++ b/source/utility/tileset_updater.cpp
@@ -72,7 +72,7 @@ void Tileset::exportTileset() const {
String exportDir = tilesetExportDir(sourcePath, sourceName);
String tilesetPath = unixFileJoin(exportDir, m_name + ".json");
File::makeDirectoryRecursive(File::dirName(tilesetPath));
- Logger::info("Updating tileset at %s", tilesetPath);
+ Logger::info("Updating tileset at {}", tilesetPath);
exportTilesetImages(exportDir);
@@ -156,7 +156,7 @@ void Tileset::exportTilesetImages(String const& exportDir) const {
String imageDir = unixFileJoin(imageDirName(exportDir), tile->database);
File::makeDirectoryRecursive(imageDir);
String imageName = unixFileJoin(imageDir, tile->name + ".png");
- Logger::info("Updating image %s", imageName);
+ Logger::info("Updating image {}", imageName);
tile->image->writePng(File::open(imageName, IOMode::Write));
}
}
@@ -166,7 +166,7 @@ Json Tileset::getTilesetJson(String const& tilesetPath) const {
return Json::parseJson(File::readFileString(tilesetPath));
} else {
Logger::warn(
- "Tileset %s wasn't already present. Creating it from scratch. Any maps already using this tileset may be "
+ "Tileset {} wasn't already present. Creating it from scratch. Any maps already using this tileset may be "
"broken.",
tilesetPath);
return JsonObject{{"margin", 0},
@@ -208,7 +208,7 @@ StringSet Tileset::updateTiles(JsonObject& tileProperties,
if (existingTiles.contains(tile->name)) {
id = existingTiles.get(tile->name);
} else {
- coutf("Adding '%s' to %s\n", tile->name, tilesetPath);
+ coutf("Adding '{}' to {}\n", tile->name, tilesetPath);
id = nextId++;
}
@@ -235,7 +235,7 @@ void Tileset::invalidateTiles(StringSet const& invalidTiles,
tileImages[toString(id)] = tileImageReference(tile->name, tile->database);
} else {
if (!tileProperties[toString(id)].contains("invalid"))
- coutf("Removing '%s' from %s\n", tileName, tilesetPath);
+ coutf("Removing '{}' from {}\n", tileName, tilesetPath);
tileProperties[toString(id)] = JsonObject{{"//name", tileName}, {"invalid", "true"}};
tileImages[toString(id)] = imageFileReference(InvalidTileImage);
}
@@ -254,7 +254,7 @@ void TilesetUpdater::defineAssetSource(String const& source) {
String tilesetDir = tilesetExportDir(sourcePath, sourceName);
String imageDir = imageExportDirName(tilesetDir, sourceName);
- Logger::info("Scanning %s for images...", imageDir);
+ Logger::info("Scanning {} for images...", imageDir);
if (!File::isDirectory(imageDir))
return;
@@ -262,7 +262,7 @@ void TilesetUpdater::defineAssetSource(String const& source) {
if (entry.second) {
String databaseName = entry.first;
String databasePath = unixFileJoin(imageDir, databaseName);
- Logger::info("Scanning database %s...", databaseName);
+ Logger::info("Scanning database {}...", databaseName);
for (pair<String, bool> image : File::dirList(databasePath)) {
starAssert(!image.second);
starAssert(image.first.endsWith(".png"));
@@ -282,7 +282,7 @@ void TilesetUpdater::exportTilesets() {
for (auto const& tilesets : m_tilesets) {
auto parsedAssetSource = parseAssetSource(tilesets.first);
if (!parsedAssetSource) {
- Logger::info("Not updating tilesets in %s because it is packed", tilesets.first);
+ Logger::info("Not updating tilesets in {} because it is packed", tilesets.first);
continue;
}
String sourceName;
@@ -302,7 +302,7 @@ void TilesetUpdater::exportTilesets() {
for (String tileName : unusedImages) {
String tileImagePath = unixFileJoin(databaseImagePath, tileName + ".png");
starAssert(File::isFile(tileImagePath));
- coutf("Removing unused tile image tiled/%s/%s/%s.png\n", sourceName, database->name(), tileName);
+ coutf("Removing unused tile image tiled/{}/{}/{}.png\n", sourceName, database->name(), tileName);
File::remove(tileImagePath);
}
m_preexistingImages[sourceName][database->name()] = database->tileNames();
diff --git a/source/utility/update_tilesets.cpp b/source/utility/update_tilesets.cpp
index e5b850b..3d689ba 100644
--- a/source/utility/update_tilesets.cpp
+++ b/source/utility/update_tilesets.cpp
@@ -179,7 +179,7 @@ void scanObjects(TilesetUpdater& updater) {
for (String const& objectName : objects->allObjects()) {
auto orientations = objects->getOrientations(objectName);
if (orientations.size() < 1) {
- Logger::warn("Object %s has no orientations and will not be exported", objectName);
+ Logger::warn("Object {} has no orientations and will not be exported", objectName);
continue;
}
@@ -244,7 +244,7 @@ int main(int argc, char** argv) {
TilesetUpdater updater;
for (String source : root->assets()->assetSources()) {
- Logger::info("Assets source: \"%s\"", source);
+ Logger::info("Assets source: \"{}\"", source);
updater.defineAssetSource(source);
}
@@ -256,7 +256,7 @@ int main(int argc, char** argv) {
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/word_count.cpp b/source/utility/word_count.cpp
index 683a3a9..d233b8c 100644
--- a/source/utility/word_count.cpp
+++ b/source/utility/word_count.cpp
@@ -31,7 +31,7 @@ int main(int argc, char** argv) {
if (json.isNull())
continue;
- String countKey = wordCountKey ? *wordCountKey : strf(".%s files", type);
+ String countKey = wordCountKey ? *wordCountKey : strf(".{} files", type);
wordCounts[countKey] += countFunction(json);
}
};
@@ -178,14 +178,14 @@ int main(int argc, char** argv) {
int totalWordCount = 0;
for (auto countPair : wordCounts) {
- coutf("%d words in %s\n", countPair.second, countPair.first);
+ coutf("{} words in {}\n", countPair.second, countPair.first);
totalWordCount += countPair.second;
}
- coutf("approximately %s words total\n", totalWordCount);
+ coutf("approximately {} words total\n", totalWordCount);
return 0;
} catch (std::exception const& e) {
- cerrf("exception caught: %s\n", outputException(e, true));
+ cerrf("exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/utility/world_benchmark.cpp b/source/utility/world_benchmark.cpp
index d9efe45..40476a1 100644
--- a/source/utility/world_benchmark.cpp
+++ b/source/utility/world_benchmark.cpp
@@ -63,7 +63,7 @@ int main(int argc, char** argv) {
for (uint64_t i = 0; i < times; ++i) {
WorldServer worldServer(worldTemplate, File::ephemeralFile());
- coutf("Starting world simulation for %s steps\n", steps);
+ coutf("Starting world simulation for {} steps\n", steps);
double start = Time::monotonicTime();
double lastReport = Time::monotonicTime();
uint64_t entityCount = 0;
@@ -79,23 +79,23 @@ int main(int argc, char** argv) {
if (reportEvery != 0 && j % reportEvery == 0) {
float fps = reportEvery / (Time::monotonicTime() - lastReport);
lastReport = Time::monotonicTime();
- coutf("[%s] %ss | FPS: %s | Entities: %s\n", j, Time::monotonicTime() - start, fps, entityCount);
+ coutf("[{}] {}s | FPS: {} | Entities: {}\n", j, Time::monotonicTime() - start, fps, entityCount);
}
worldServer.update();
}
double totalTime = Time::monotonicTime() - start;
- coutf("Finished run of running dungeon world '%s' with seed %s for %s steps in %s seconds, average FPS: %s\n",
+ coutf("Finished run of running dungeon world '{}' with seed {} for {} steps in {} seconds, average FPS: {}\n",
dungeon, worldSeed, steps, totalTime, steps / totalTime);
sumTime += totalTime;
}
if (times != 1) {
- coutf("Average of all runs - time: %s, FPS: %s\n", sumTime / times, steps / (sumTime / times));
+ coutf("Average of all runs - time: {}, FPS: {}\n", sumTime / times, steps / (sumTime / times));
}
return 0;
} catch (std::exception const& e) {
- cerrf("Exception caught: %s\n", outputException(e, true));
+ cerrf("Exception caught: {}\n", outputException(e, true));
return 1;
}
}
diff --git a/source/windowing/StarFuelWidget.cpp b/source/windowing/StarFuelWidget.cpp
index 43ea3d5..af51cb2 100644
--- a/source/windowing/StarFuelWidget.cpp
+++ b/source/windowing/StarFuelWidget.cpp
@@ -86,7 +86,7 @@ void FuelWidget::renderImpl() {
guiContext.setFontColor(Color::White.toRgba());
}
- guiContext.renderInterfaceText(strf("Fuel %s/%s", std::min(m_fuelLevel + m_potential, m_maxLevel), (int)m_maxLevel),
+ guiContext.renderInterfaceText(strf("Fuel {}/{}", std::min(m_fuelLevel + m_potential, m_maxLevel), (int)m_maxLevel),
{textPosition, HorizontalAnchor::HMidAnchor, VerticalAnchor::VMidAnchor});
}
diff --git a/source/windowing/StarGuiReader.cpp b/source/windowing/StarGuiReader.cpp
index 4e02529..f44706a 100644
--- a/source/windowing/StarGuiReader.cpp
+++ b/source/windowing/StarGuiReader.cpp
@@ -38,10 +38,10 @@ WidgetConstructResult GuiReader::titleHandler(String const&, Json const& config)
String type = iconConfig.getString("type");
auto icon = m_constructors.get(type)("icon", iconConfig);
if (!icon.obj)
- throw WidgetParserException(strf("Title specified incompatible icon type: %s", type));
+ throw WidgetParserException(strf("Title specified incompatible icon type: {}", type));
m_pane->setTitle(icon.obj, title, subtitle);
} catch (JsonException const& e) {
- throw WidgetParserException(strf("Malformed icon configuration data in title. %s", outputException(e, false)));
+ throw WidgetParserException(strf("Malformed icon configuration data in title. {}", outputException(e, false)));
}
}
} else {
@@ -74,7 +74,7 @@ WidgetConstructResult GuiReader::backgroundHandler(String const&, Json const& co
footer = config.getString("fileFooter", "");
} catch (MapException const& e) {
throw WidgetParserException(
- strf("Malformed gui json, missing a required value in the map. %s", outputException(e, false)));
+ strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
}
m_pane->setBG(header, body, footer);
diff --git a/source/windowing/StarGuiTypes.cpp b/source/windowing/StarGuiTypes.cpp
index 2085426..80ac5fd 100644
--- a/source/windowing/StarGuiTypes.cpp
+++ b/source/windowing/StarGuiTypes.cpp
@@ -23,7 +23,7 @@ EnumMap<GuiDirection> const GuiDirectionNames{
};
String rarityBorder(Rarity rarity) {
- return strf("/interface/inventory/itemborder%s.png", RarityNames.getRight(rarity).toLower());
+ return strf("/interface/inventory/itemborder{}.png", RarityNames.getRight(rarity).toLower());
}
}
diff --git a/source/windowing/StarItemGridWidget.cpp b/source/windowing/StarItemGridWidget.cpp
index 624385b..ad02c32 100644
--- a/source/windowing/StarItemGridWidget.cpp
+++ b/source/windowing/StarItemGridWidget.cpp
@@ -155,7 +155,7 @@ void ItemGridWidget::setItemBag(ItemBagConstPtr bag) {
m_slots.clear();
for (size_t i = 0; i < m_bag->size() - m_bagOffset && i < (unsigned)m_dimensions[0] * m_dimensions[1]; ++i) {
auto itemSlot = make_shared<ItemSlotWidget>(m_bag->at(i), m_backingImage);
- addChild(strf("%d", i), itemSlot);
+ addChild(strf("{}", i), itemSlot);
m_slots.append(itemSlot);
itemSlot->setBackingImageAffinity(m_drawBackingImageWhenFull, m_drawBackingImageWhenEmpty);
itemSlot->setProgress(m_progress);
diff --git a/source/windowing/StarItemSlotWidget.cpp b/source/windowing/StarItemSlotWidget.cpp
index a828838..cf12a8d 100644
--- a/source/windowing/StarItemSlotWidget.cpp
+++ b/source/windowing/StarItemSlotWidget.cpp
@@ -178,20 +178,20 @@ void ItemSlotWidget::renderImpl() {
}
int frame = (int)roundf(m_progress * 18); // TODO: Hardcoded lol
- context()->drawInterfaceQuad(String(strf("/interface/cooldown.png:%d", frame)), Vec2F(screenPosition()));
+ context()->drawInterfaceQuad(String(strf("/interface/cooldown.png:{}", frame)), Vec2F(screenPosition()));
if (m_item->count() > 1 && m_showCount) { // we don't need to tell people that there's only 1 of something
context()->setFont(m_font);
context()->setFontSize(m_fontSize);
context()->setFontColor(m_fontColor.toRgba());
context()->setFontMode(m_countFontMode);
- context()->renderInterfaceText(strf("%d", m_item->count()), m_countPosition.translated(Vec2F(screenPosition())));
+ context()->renderInterfaceText(strf("{}", m_item->count()), m_countPosition.translated(Vec2F(screenPosition())));
}
} else if (m_drawBackingImageWhenEmpty && m_backingImage != "") {
context()->drawInterfaceQuad(m_backingImage, Vec2F(screenPosition()));
int frame = (int)roundf(m_progress * 18); // TODO: Hardcoded lol
- context()->drawInterfaceQuad(String(strf("/interface/cooldown.png:%d", frame)), Vec2F(screenPosition()));
+ context()->drawInterfaceQuad(String(strf("/interface/cooldown.png:{}", frame)), Vec2F(screenPosition()));
}
if (m_highlightEnabled) {
diff --git a/source/windowing/StarKeyBindings.cpp b/source/windowing/StarKeyBindings.cpp
index e93a1af..969a766 100644
--- a/source/windowing/StarKeyBindings.cpp
+++ b/source/windowing/StarKeyBindings.cpp
@@ -107,10 +107,10 @@ KeyChord inputDescriptorFromJson(Json const& json) {
} else if (value.canConvert(Json::Type::Int)) {
key = (Key)value.toUInt();
} else {
- throw StarException::format("Improper key value '%s'", value);
+ throw StarException::format("Improper key value '{}'", value);
}
} else {
- throw StarException::format("Improper bindings type '%s'", type);
+ throw StarException::format("Improper bindings type '{}'", type);
}
KeyMod mods = KeyMod::NoMod;
@@ -156,7 +156,7 @@ KeyBindings::KeyBindings(Json const& json) {
auto chord = inputDescriptorFromJson(input);
actions[chord.key].append({chord.mods, action});
} catch (StarException const& e) {
- Logger::warn("Could not load keybinding for %s: %s\n",
+ Logger::warn("Could not load keybinding for {}: {}\n",
InterfaceActionNames.getRight(action),
outputException(e, false));
}
@@ -165,7 +165,7 @@ KeyBindings::KeyBindings(Json const& json) {
m_actions = move(actions);
} catch (StarException const& e) {
- throw StarException(strf("Could not set keybindings from configuration. %s", outputException(e, false)));
+ throw StarException(strf("Could not set keybindings from configuration. {}", outputException(e, false)));
}
}
diff --git a/source/windowing/StarListWidget.cpp b/source/windowing/StarListWidget.cpp
index cda7f92..993fb73 100644
--- a/source/windowing/StarListWidget.cpp
+++ b/source/windowing/StarListWidget.cpp
@@ -63,14 +63,14 @@ void ListWidget::setSchema(Json const& schema) {
m_spacing = jsonToVec2I(schema.get("spacing"));
m_memberSize = jsonToVec2I(schema.get("memberSize"));
} catch (JsonException const& e) {
- throw GuiException(strf("Missing required value in map: %s", outputException(e, false)));
+ throw GuiException(strf("Missing required value in map: {}", outputException(e, false)));
}
updateSizeAndPosition();
}
WidgetPtr ListWidget::addItem() {
auto newItem = constructWidget();
- addChild(strf("%d", Random::randu64()), newItem);
+ addChild(strf("{}", Random::randu64()), newItem);
updateSizeAndPosition();
return newItem;
@@ -78,7 +78,7 @@ WidgetPtr ListWidget::addItem() {
WidgetPtr ListWidget::addItem(size_t at) {
auto newItem = constructWidget();
- addChildAt(strf("%d", Random::randu64()), newItem, at);
+ addChildAt(strf("{}", Random::randu64()), newItem, at);
updateSizeAndPosition();
if (m_selectedItem != NPos && at <= m_selectedItem)
@@ -88,7 +88,7 @@ WidgetPtr ListWidget::addItem(size_t at) {
}
WidgetPtr ListWidget::addItem(WidgetPtr existingItem) {
- addChild(strf("%d", Random::randu64()), existingItem);
+ addChild(strf("{}", Random::randu64()), existingItem);
updateSizeAndPosition();
return existingItem;
diff --git a/source/windowing/StarRegisteredPaneManager.hpp b/source/windowing/StarRegisteredPaneManager.hpp
index fb17ee5..4038525 100644
--- a/source/windowing/StarRegisteredPaneManager.hpp
+++ b/source/windowing/StarRegisteredPaneManager.hpp
@@ -50,7 +50,7 @@ template <typename T>
shared_ptr<T> RegisteredPaneManager<KeyT>::registeredPane(KeyT const& paneId) const {
if (auto v = m_registeredPanes.ptr(paneId))
return convert<T>(v->pane);
- throw GuiException(strf("No pane named '%s' found in RegisteredPaneManager", outputAny(paneId)));
+ throw GuiException(strf("No pane named '{}' found in RegisteredPaneManager", outputAny(paneId)));
}
template <typename KeyT>
@@ -58,7 +58,7 @@ void RegisteredPaneManager<KeyT>::registerPane(
KeyT paneId, PaneLayer paneLayer, PanePtr pane, DismissCallback onDismiss) {
if (!m_registeredPanes.insert(move(paneId), {move(paneLayer), move(pane), move(onDismiss)}).second)
throw GuiException(
- strf("Registered pane with name '%s' registered a second time in RegisteredPaneManager::registerPane",
+ strf("Registered pane with name '{}' registered a second time in RegisteredPaneManager::registerPane",
outputAny(paneId)));
}
@@ -69,7 +69,7 @@ PanePtr RegisteredPaneManager<KeyT>::deregisterPane(KeyT const& paneId) {
dismissPane(v->pane);
return v->pane;
}
- throw GuiException(strf("No pane named '%s' found in RegisteredPaneManager::deregisterPane", outputAny(paneId)));
+ throw GuiException(strf("No pane named '{}' found in RegisteredPaneManager::deregisterPane", outputAny(paneId)));
}
template <typename KeyT>
@@ -119,7 +119,7 @@ typename RegisteredPaneManager<KeyT>::PaneInfo const& RegisteredPaneManager<KeyT
KeyT const& paneId) const {
if (auto p = m_registeredPanes.ptr(paneId))
return *p;
- throw GuiException(strf("No registered pane with name '%s' found in RegisteredPaneManager", outputAny(paneId)));
+ throw GuiException(strf("No registered pane with name '{}' found in RegisteredPaneManager", outputAny(paneId)));
}
}
diff --git a/source/windowing/StarSliderBar.cpp b/source/windowing/StarSliderBar.cpp
index 12fb749..e25ed4f 100644
--- a/source/windowing/StarSliderBar.cpp
+++ b/source/windowing/StarSliderBar.cpp
@@ -39,17 +39,17 @@ SliderBarWidget::SliderBarWidget(String const& grid, bool showSpinner)
// TODO: Make spinners a thing already
Json config = Json::parse(strf(
R"SPINNER(
- {
- "spinner" : {
+ {{
+ "spinner" : {{
"type" : "spinner",
- "leftBase" : "%s",
- "leftHover" : "%s",
- "rightBase" : "%s",
- "rightHover" : "%s",
+ "leftBase" : "{}",
+ "leftHover" : "{}",
+ "rightBase" : "{}",
+ "rightHover" : "{}",
"position" : [0, 0],
- "upOffset" : %s
- }
- }
+ "upOffset" : {}
+ }}
+ }}
)SPINNER",
assets->json("/interface.config:slider.leftBase").toString(),
assets->json("/interface.config:slider.leftHover").toString(),
diff --git a/source/windowing/StarWidget.cpp b/source/windowing/StarWidget.cpp
index 3189f8a..518b922 100644
--- a/source/windowing/StarWidget.cpp
+++ b/source/windowing/StarWidget.cpp
@@ -427,15 +427,15 @@ String Widget::toStringImpl(int indentLevel) const {
for (auto child : m_members) {
childrenString.append(child->toStringImpl(indentLevel + 4));
}
- String output = strf(R"OUTPUT(%s%s : {
-%s address : %p,
-%s visible : %s,
-%s position : %s,
-%s size : %s,
-%s children : {
-%s
-%s }
-%s}
+ String output = strf(R"OUTPUT({}{} : {
+{} address : %p,
+{} visible : {},
+{} position : {},
+{} size : {},
+{} children : {
+{}
+{} }
+{}}
)OUTPUT",
leader,
m_name,
diff --git a/source/windowing/StarWidgetParsing.cpp b/source/windowing/StarWidgetParsing.cpp
index 4ffc921..c7bc69e 100644
--- a/source/windowing/StarWidgetParsing.cpp
+++ b/source/windowing/StarWidgetParsing.cpp
@@ -75,7 +75,7 @@ void WidgetParser::constructImpl(Json const& config, Widget* widget) {
WidgetPtr WidgetParser::makeSingle(String const& name, Json const& config) {
if (!m_constructors.contains(config.getString("type"))) {
- throw WidgetParserException(strf("Unknown type in gui json. %s", config.getString("type")));
+ throw WidgetParserException(strf("Unknown type in gui json. {}", config.getString("type")));
}
auto constructResult = m_constructors.get(config.getString("type"))(name, config);
@@ -94,7 +94,7 @@ List<WidgetConstructResult> WidgetParser::constructor(Json const& config) {
widgets.appendAll(constructor(Root::singleton().assets()->json(memberConfig.getString("file"))));
} else {
if (!m_constructors.contains(type)) {
- throw WidgetParserException(strf("Unknown type in gui json. %s", type));
+ throw WidgetParserException(strf("Unknown type in gui json. {}", type));
}
auto constructResult =
m_constructors.get(memberConfig.getString("type"))(memberConfig.getString("name"), memberConfig);
@@ -110,7 +110,7 @@ List<WidgetConstructResult> WidgetParser::constructor(Json const& config) {
for (auto const& elem : config.iterateArray())
addWidget(elem);
} else {
- throw WidgetParserException(strf("Malformed gui json, expected a Map or a List. Instead got %s", config));
+ throw WidgetParserException(strf("Malformed gui json, expected a Map or a List. Instead got {}", config));
}
return widgets;
@@ -129,7 +129,7 @@ WidgetConstructResult WidgetParser::buttonHandler(String const& name, Json const
baseImage = config.getString("base");
} catch (MapException const& e) {
throw WidgetParserException(
- strf("Malformed gui json, missing a required value in the map. %s", outputException(e, false)));
+ strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
}
String hoverImage = config.getString("hover", "");
@@ -144,7 +144,7 @@ WidgetConstructResult WidgetParser::buttonHandler(String const& name, Json const
String callback = config.getString("callback", name);
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find callback named: %s", callback);
+ throw WidgetParserException::format("Failed to find callback named: {}", callback);
WidgetCallbackFunc callbackFunc = m_callbacks.get(callback);
auto button = make_shared<ButtonWidget>(callbackFunc, baseImage, hoverImage, pressedImage, disabledImage);
@@ -177,7 +177,7 @@ WidgetConstructResult WidgetParser::buttonHandler(String const& name, Json const
button->setTextAlign(HorizontalAnchor::LeftAnchor);
} else {
throw WidgetParserException(strf(
- "Malformed gui json, expected textAlign to be one of \"left\", \"right\", or \"center\", got %s", hAnchor));
+ "Malformed gui json, expected textAlign to be one of \"left\", \"right\", or \"center\", got {}", hAnchor));
}
if (config.contains("fontSize"))
@@ -251,9 +251,9 @@ WidgetConstructResult WidgetParser::spinnerHandler(String const& name, Json cons
String callback = config.getString("callback", name);
if (!m_callbacks.contains(callback + ".up"))
- throw WidgetParserException::format("Failed to find spinner callback named: '%s.up'", name);
+ throw WidgetParserException::format("Failed to find spinner callback named: '{}.up'", name);
if (!m_callbacks.contains(callback + ".down"))
- throw WidgetParserException::format("Failed to find spinner callback named: '%s.down'", name);
+ throw WidgetParserException::format("Failed to find spinner callback named: '{}.down'", name);
WidgetCallbackFunc callbackDown = m_callbacks.get(callback + ".down");
WidgetCallbackFunc callbackUp = m_callbacks.get(callback + ".up");
@@ -301,11 +301,11 @@ WidgetConstructResult WidgetParser::radioGroupHandler(String const& name, Json c
buttons = config.getArray("buttons");
} catch (MapException const& e) {
throw WidgetParserException(
- strf("Malformed gui json, missing a required value in the map. %s", outputException(e, false)));
+ strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
}
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find callback named: '%s'", callback);
+ throw WidgetParserException::format("Failed to find callback named: '{}'", callback);
String baseImage = config.getString("baseImage", "");
String hoverImage = config.getString("hoverImage", "");
@@ -360,10 +360,10 @@ WidgetConstructResult WidgetParser::radioGroupHandler(String const& name, Json c
common(button, btnConfig);
- buttonGroup->addChild(strf("%d", button->buttonGroupId()), button);
+ buttonGroup->addChild(strf("{}", button->buttonGroupId()), button);
} catch (MapException const& e) {
throw WidgetParserException(
- strf("Malformed gui json, missing a required value in the map. %s", outputException(e, false)));
+ strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
}
}
@@ -390,7 +390,7 @@ WidgetConstructResult WidgetParser::textboxHandler(String const& name, Json cons
String callback = config.getString("callback", name);
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find textbox callback named: '%s'", name);
+ throw WidgetParserException::format("Failed to find textbox callback named: '{}'", name);
WidgetCallbackFunc callbackFunc = m_callbacks.get(callback);
@@ -417,7 +417,7 @@ WidgetConstructResult WidgetParser::textboxHandler(String const& name, Json cons
textbox->setTextAlign(HorizontalAnchor::HMidAnchor);
} else if (hAnchor != "left") {
throw WidgetParserException(strf(
- "Malformed gui json, expected textAlign to be one of \"left\", \"right\", or \"center\", got %s", hAnchor));
+ "Malformed gui json, expected textAlign to be one of \"left\", \"right\", or \"center\", got {}", hAnchor));
}
if (config.contains("fontSize"))
@@ -477,11 +477,11 @@ WidgetConstructResult WidgetParser::itemSlotHandler(String const& name, Json con
auto itemSlot = make_shared<ItemSlotWidget>(ItemPtr(), backingImage);
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find itemSlot callback named: '%s'", callback);
+ throw WidgetParserException::format("Failed to find itemSlot callback named: '{}'", callback);
itemSlot->setCallback(m_callbacks.get(callback));
if (!m_callbacks.contains(rightClickCallback))
- throw WidgetParserException::format("Failed to find itemslot rightClickCallback named: '%s'", rightClickCallback);
+ throw WidgetParserException::format("Failed to find itemslot rightClickCallback named: '{}'", rightClickCallback);
itemSlot->setRightClickCallback(m_callbacks.get(rightClickCallback));
itemSlot->setBackingImageAffinity(config.getBool("showBackingImageWhenFull", false), config.getBool("showBackingImageWhenEmpty", true));
@@ -509,7 +509,7 @@ WidgetConstructResult WidgetParser::itemGridHandler(String const& name, Json con
columnSpacing = jsonToVec2I(config.get("columnSpacing"));
}
} catch (MapException const& e) {
- throw WidgetParserException::format("Malformed gui json, missing a required value in the map. %s", outputException(e, false));
+ throw WidgetParserException::format("Malformed gui json, missing a required value in the map. {}", outputException(e, false));
}
String backingImage = config.getString("backingImage", "");
@@ -526,7 +526,7 @@ WidgetConstructResult WidgetParser::itemGridHandler(String const& name, Json con
auto itemGrid = make_shared<ItemGridWidget>(ItemBagConstPtr(), dimensions, rowSpacing, columnSpacing, backingImage, slotOffset);
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find itemgrid callback named: '%s'", callback);
+ throw WidgetParserException::format("Failed to find itemgrid callback named: '{}'", callback);
itemGrid->setCallback(m_callbacks.get(callback));
@@ -535,7 +535,7 @@ WidgetConstructResult WidgetParser::itemGridHandler(String const& name, Json con
itemGrid->showDurability(config.getBool("showDurability", false));
if (!m_callbacks.contains(rightClickCallback))
- throw WidgetParserException::format("Failed to find itemgrid rightClickCallback named: '%s'", rightClickCallback);
+ throw WidgetParserException::format("Failed to find itemgrid rightClickCallback named: '{}'", rightClickCallback);
itemGrid->setRightClickCallback(m_callbacks.get(rightClickCallback));
@@ -550,7 +550,7 @@ WidgetConstructResult WidgetParser::listHandler(String const& name, Json const&
schema = config.get("schema");
} catch (MapException const& e) {
throw WidgetParserException(
- strf("Malformed gui json, missing a required value in the map. %s", outputException(e, false)));
+ strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
}
auto list = make_shared<ListWidget>(schema);
@@ -593,7 +593,7 @@ WidgetConstructResult WidgetParser::sliderHandler(String const& name, Json const
return WidgetConstructResult(slider, name, config.getFloat("zlevel", 0));
} catch (MapException const& e) {
throw WidgetParserException::format(
- "Malformed gui json, missing a required value in the map. %s", outputException(e, false));
+ "Malformed gui json, missing a required value in the map. {}", outputException(e, false));
}
}
@@ -601,7 +601,7 @@ WidgetConstructResult WidgetParser::largeCharPlateHandler(String const& name, Js
String callback = config.getString("callback", name);
if (!m_callbacks.contains(callback))
- throw WidgetParserException::format("Failed to find callback named: '%s'", name);
+ throw WidgetParserException::format("Failed to find callback named: '{}'", name);
auto charPlate = make_shared<LargeCharPlateWidget>(m_callbacks.get(callback));
common(charPlate, config);
@@ -639,7 +639,7 @@ WidgetConstructResult WidgetParser::tabSetHandler(String const& name, Json const
tabSet->addTab(entry.getString("tabName"), widget, entry.getString("tabTitle"));
}
} catch (JsonException const& e) {
- throw WidgetParserException(strf("Malformed gui json. %s", outputException(e, false)));
+ throw WidgetParserException(strf("Malformed gui json. {}", outputException(e, false)));
}
return WidgetConstructResult(tabSet, name, config.getFloat("zlevel", 0));
@@ -673,7 +673,7 @@ WidgetConstructResult WidgetParser::layoutHandler(String const& name, Json const
try {
flow->setSpacing(jsonToVec2I(config.get("spacing")));
} catch (JsonException const& e) {
- throw WidgetParserException(strf("Parameter \"spacing\" in FlowLayout specification is invalid: %s.", outputException(e, false)));
+ throw WidgetParserException(strf("Parameter \"spacing\" in FlowLayout specification is invalid: {}.", outputException(e, false)));
}
} else if (type == "vertical") {
widget = make_shared<VerticalLayout>();
@@ -685,7 +685,7 @@ WidgetConstructResult WidgetParser::layoutHandler(String const& name, Json const
} else if (type == "basic") {
widget = make_shared<Layout>();
} else {
- throw WidgetParserException(strf("Invalid layout type \"%s\". Options are \"basic\", \"flow\", \"vertical\".", type));
+ throw WidgetParserException(strf("Invalid layout type \"{}\". Options are \"basic\", \"flow\", \"vertical\".", type));
}
common(widget, config);
if (config.contains("children"))
@@ -745,7 +745,7 @@ WidgetConstructResult WidgetParser::stackHandler(String const& name, Json const&
auto widget = make_shared<Widget>();
constructImpl(widgetCfg, widget.get());
widget->determineSizeFromChildren();
- stack->addChild(strf("%d", stack->numChildren()), widget);
+ stack->addChild(strf("{}", stack->numChildren()), widget);
}
}
@@ -811,7 +811,7 @@ ImageStretchSet WidgetParser::parseImageStretchSet(Json const& config) {
} else if (type == "stretch") {
res.type = ImageStretchSet::ImageStretchType::Stretch;
} else {
- throw WidgetParserException(strf("Could not parse Image Stretch Set, unknown type: %s"));
+ throw WidgetParserException(strf("Could not parse Image Stretch Set, unknown type: {}"));
}
return res;