Change pure string format calls to use fmt::to_string

This commit is contained in:
Kae 2023-07-06 19:26:28 +10:00
parent f75d1f0b5a
commit fe4cc19618
26 changed files with 51 additions and 51 deletions

View File

@ -108,7 +108,7 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, Maybe<pa
}
if (auto lobby = m_discordServerLobby)
activity.GetParty().SetId(strf("{}", lobby->first).c_str());
activity.GetParty().SetId(toString(lobby->first).c_str());
if (m_joinLocation.is<JoinLocal>()) {
if (auto lobby = m_discordServerLobby) {
@ -117,7 +117,7 @@ void Star::PcP2PNetworkingService::setActivityData(String const& title, Maybe<pa
activity.GetSecrets().SetJoin(joinSecret.utf8Ptr());
}
} else if (m_joinLocation.is<JoinRemote>()) {
String address = strf("{}", (HostAddressWithPort)m_joinLocation.get<JoinRemote>());
String address = toString((HostAddressWithPort)m_joinLocation.get<JoinRemote>());
String joinSecret = strf("connect:address_{}", address);
Logger::info("Setting discord join secret as {}", joinSecret);
activity.GetSecrets().SetJoin(joinSecret.utf8Ptr());

View File

@ -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("{}", y * dimensions[0] + x)] =
framesSpecification.frames[toString(y * dimensions[0] + x)] =
RectU::withSize(Vec2U(begin[0] + x * size[0], begin[1] + y * size[1]), size);
}
}

View File

@ -234,7 +234,7 @@ void ClientApplication::renderInit(RendererPtr renderer) {
};
loadEffectConfig("world");
loadEffectConfig("default");
loadEffectConfig("interface");
if (m_root->configuration()->get("limitTextureAtlasSize").optBool().value(false))
renderer->setSizeLimitEnabled(true);
@ -389,11 +389,11 @@ void ClientApplication::render() {
WorldClientPtr worldClient = m_universeClient->worldClient();
RendererPtr renderer = Application::renderer();
renderer->switchEffectConfig("world");
if (worldClient) {
auto totalStart = Time::monotonicMicroseconds();
auto start = totalStart;
renderer->switchEffectConfig("world");
worldClient->render(m_renderData, TilePainter::BorderTileSize);
LogMap::set("client_render_world_client", strf(u8"{:05d}\u00b5s", Time::monotonicMicroseconds() - start));
@ -404,10 +404,10 @@ void ClientApplication::render() {
start = Time::monotonicMicroseconds();
m_mainInterface->renderInWorldElements();
LogMap::set("client_render_world_elements", strf(u8"{:05d}\u00b5s", Time::monotonicMicroseconds() - start));
renderer->switchEffectConfig("default");
LogMap::set("client_render_world_total", strf(u8"{:05d}\u00b5s", Time::monotonicMicroseconds() - totalStart));
}
renderer->switchEffectConfig("interface");
auto start = Time::monotonicMicroseconds();
m_mainInterface->render();
m_cinematicOverlay->render();
@ -879,8 +879,8 @@ void ClientApplication::updateRunning() {
LogMap::set("player_vel", strf("[ ^#f45;{:4.2f}^reset;, ^#49f;{:4.2f}^reset; ]", m_player->velocity()[0], m_player->velocity()[1]));
LogMap::set("player_aim", strf("[ ^#f45;{:4.2f}^reset;, ^#49f;{:4.2f}^reset; ]", aimPosition[0], aimPosition[1]));
if (m_universeClient->worldClient()) {
LogMap::set("tile_liquid_level", strf("{}", m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level));
LogMap::set("tile_dungeon_id", strf("{}", m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition))));
LogMap::set("tile_liquid_level", toString(m_universeClient->worldClient()->liquidLevel(Vec2I::floor(aimPosition)).level));
LogMap::set("tile_dungeon_id", toString(m_universeClient->worldClient()->dungeonId(Vec2I::floor(aimPosition))));
}
if (m_mainInterface->currentState() == MainInterface::ReturnToTitle)

View File

@ -40,6 +40,11 @@ void cerrf(char const* fmt, Args const&... args) {
std::cerr.flush();
}
template <class Type>
inline std::string toString(Type const& t) {
return fmt::to_string(t);
}
}
#endif

View File

@ -42,11 +42,6 @@ Type lexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::bo
throw BadLexicalCast(strf("Lexical cast failed on '{}'", s));
}
template <class Type>
std::string toString(Type const& t) {
return fmt::to_string(t);
}
}
#endif

View File

@ -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("{}", t));
setValue(key, toString(t));
}
}

View File

@ -189,7 +189,7 @@ void Cinematic::render() {
m_completable = true;
if (!values.alpha)
continue;
auto frame = strf("{}", ((int)values.frame) % panel->animationFrames);
auto frame = toString(((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}})));

View File

@ -127,7 +127,7 @@ String ClientCommandProcessor::gravity() {
if (!adminCommandAllowed())
return "You must be an admin to use this command.";
return strf("{}", m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
return toString(m_universeClient->worldClient()->gravity(m_universeClient->mainPlayer()->position()));
}
String ClientCommandProcessor::debug(StringList const& arguments) {

View File

@ -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("{}", container->containerSize())));
countWidget->setText(countWidget->text().replace("<slots>", toString(container->containerSize())));
m_itemBag = make_shared<ItemBag>(container->containerSize());
auto items = container->containerItems();

View File

@ -294,7 +294,7 @@ void CraftingPane::update() {
updateCraftButtons();
}
setLabel("lblPlayerMoney", strf("{}", (int)m_player->currency("money")));
setLabel("lblPlayerMoney", toString((int)m_player->currency("money")));
Pane::update();
}
@ -421,7 +421,7 @@ void CraftingPane::setupWidget(WidgetPtr const& widget, ItemRecipe const& recipe
}
if (price > 0) {
widget->setLabel("priceLabel", strf("{}", price));
widget->setLabel("priceLabel", toString(price));
if (auto icon = widget->fetchChild<ImageWidget>("moneyIcon"))
icon->setVisibility(true);
} else {

View File

@ -317,25 +317,25 @@ void InventoryPane::update() {
techOverlay->setVisibility(m_player->techOverridden());
auto healthLabel = fetchChild<LabelWidget>("healthtext");
healthLabel->setText(strf("{}", m_player->maxHealth()));
healthLabel->setText(toString(m_player->maxHealth()));
auto energyLabel = fetchChild<LabelWidget>("energytext");
energyLabel->setText(strf("{}", m_player->maxEnergy()));
energyLabel->setText(toString(m_player->maxEnergy()));
auto weaponLabel = fetchChild<LabelWidget>("weapontext");
weaponLabel->setText(strf("{}%", ceil(m_player->powerMultiplier() * 100)));
auto defenseLabel = fetchChild<LabelWidget>("defensetext");
if (m_player->protection() == 0)
defenseLabel->setText("--");
else
defenseLabel->setText(strf("{}", ceil(m_player->protection())));
defenseLabel->setText(toString(ceil(m_player->protection())));
auto moneyLabel = fetchChild<LabelWidget>("lblMoney");
moneyLabel->setText(strf("{}", m_player->currency("money")));
moneyLabel->setText(toString(m_player->currency("money")));
if (m_player->currency("essence") > 0) {
fetchChild<ImageWidget>("imgEssenceIcon")->show();
auto essenceLabel = fetchChild<LabelWidget>("lblEssence");
essenceLabel->show();
essenceLabel->setText(strf("{}", m_player->currency("essence")));
essenceLabel->setText(toString(m_player->currency("essence")));
} else {
fetchChild<ImageWidget>("imgEssenceIcon")->hide();
fetchChild<LabelWidget>("lblEssence")->hide();

View File

@ -81,7 +81,7 @@ void ItemTooltipBuilder::buildItemDescriptionInner(
container->fetchChild<ItemSlotWidget>("icon")->setItem(item);
container->setLabel("nameLabel", item->name());
container->setLabel("countLabel", strf("{}", item->count()));
container->setLabel("countLabel", toString(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("{}", item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
container->setLabel("priceLabel", strf("{}", (int)item->price()));
container->setLabel("countLabel", toString(item->instanceValue("fuelAmount", 0).toUInt() * item->count()));
container->setLabel("priceLabel", toString((int)item->price()));
if (auto objectItem = as<ObjectItem>(item)) {
try {

View File

@ -682,7 +682,7 @@ void MainInterface::update() {
}
m_messageOverflow++;
m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", strf("{}", m_messageOverflow));
m_overflowMessage->message = m_config->overflowMessageText.replace("<count>", toString(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;

View File

@ -242,7 +242,7 @@ void MerchantPane::setupWidget(WidgetPtr const& widget, Json const& itemConfig)
itemName->setText(name);
unsigned price = ceil(itemConfig.getInt("price", item->price()) * m_buyFactor);
widget->setLabel("priceLabel", strf("{}", price));
widget->setLabel("priceLabel", toString(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("{}", m_buyTotal));
m_buyTotalLabel->setText(toString(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("{}", m_sellTotal));
m_sellTotalLabel->setText(toString(m_sellTotal));
if (m_sellTotal > 0)
m_sellButton->enable();
else

View File

@ -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("{}", m_quest->money()));
moneyLabel->setText(toString(m_quest->money()));
disableScissoring();
}

View File

@ -162,7 +162,7 @@ void TeamBar::buildTeamBar() {
continue;
}
String cellName = strf("{}", controlIndex);
String cellName = toString(controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell) {
@ -234,7 +234,7 @@ void TeamBar::buildTeamBar() {
noInviteImage->setVisibility(!couldInvite);
while (true) {
String cellName = strf("{}", controlIndex);
String cellName = toString(controlIndex);
WidgetPtr cell = list->fetchChild(cellName);
if (!cell)
break;

View File

@ -559,7 +559,7 @@ LuaCallbacks Monster::makeMonsterCallbacks() {
});
callbacks.registerCallback("seed", [this]() {
return strf("{}", m_monsterVariant.seed);
return toString(m_monsterVariant.seed);
});
callbacks.registerCallback("uniqueParameters", [this]() {

View File

@ -314,7 +314,7 @@ Json SystemWorldServer::diskStore() {
void SystemWorldServer::placeInitialObjects() {
auto config = Root::singleton().assets()->json("/systemworld.config");
RandomSource rand(staticRandomU64("SystemWorldGeneration", strf("{}", m_location)));
RandomSource rand(staticRandomU64("SystemWorldGeneration", toString(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("{}", m_location));
uint64_t seed = staticRandomU64(toString(m_location));
List<CelestialParameters> worlds;
if (auto planet = m_celestialDatabase->parameters(orbitTarget))
worlds.append(*planet);

View File

@ -1057,7 +1057,7 @@ void WorldClient::update() {
renderCollisionDebug();
LogMap::set("client_entities", m_entityMap->size());
LogMap::set("client_sectors", strf("{}", loadedSectors.size()));
LogMap::set("client_sectors", toString(loadedSectors.size()));
LogMap::set("client_lua_mem", m_luaRoot->luaMemoryUsage());
}
@ -1244,7 +1244,7 @@ void WorldClient::handleDamageNotifications() {
return;
Particle particle = Root::singleton().particleDatabase()->particle(damageNumberParticleKind);
particle.position += position;
particle.string = particle.string.replace("$dmg$", strf("{}", displayValue));
particle.string = particle.string.replace("$dmg$", toString(displayValue));
m_particles->add(particle);
};

View File

@ -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("{}", i)));
m_animationFrame.append(m_image.replace("{frame}", toString(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("{}", i)));
m_animationFrame.append(m_image.replace("{frame}", toString(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("{}", i)));
m_animationFrame.append(m_image.replace("{frame}", toString(i)));
m_idleFrame = m_image.replace("{frame}", "idle");
m_handPosition = jsonToVec2F(instanceValue("handPosition"));

View File

@ -204,7 +204,7 @@ InteractAction ContainerObject::interact(InteractRequest const&) {
}
Json ContainerObject::containerGuiConfig() const {
return Root::singleton().assets()->json(configValue("uiConfig").toString().replace("<slots>", strf("{}", m_items->size())));
return Root::singleton().assets()->json(configValue("uiConfig").toString().replace("<slots>", toString(m_items->size())));
}
String ContainerObject::containerDescription() const {

View File

@ -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("{}", i), itemSlot);
addChild(toString(i), itemSlot);
m_slots.append(itemSlot);
itemSlot->setBackingImageAffinity(m_drawBackingImageWhenFull, m_drawBackingImageWhenEmpty);
itemSlot->setProgress(m_progress);

View File

@ -185,7 +185,7 @@ void ItemSlotWidget::renderImpl() {
context()->setFontSize(m_fontSize);
context()->setFontColor(m_fontColor.toRgba());
context()->setFontMode(m_countFontMode);
context()->renderInterfaceText(strf("{}", m_item->count()), m_countPosition.translated(Vec2F(screenPosition())));
context()->renderInterfaceText(toString(m_item->count()), m_countPosition.translated(Vec2F(screenPosition())));
}
} else if (m_drawBackingImageWhenEmpty && m_backingImage != "") {

View File

@ -70,7 +70,7 @@ void ListWidget::setSchema(Json const& schema) {
WidgetPtr ListWidget::addItem() {
auto newItem = constructWidget();
addChild(strf("{}", Random::randu64()), newItem);
addChild(toString(Random::randu64()), newItem);
updateSizeAndPosition();
return newItem;
@ -78,7 +78,7 @@ WidgetPtr ListWidget::addItem() {
WidgetPtr ListWidget::addItem(size_t at) {
auto newItem = constructWidget();
addChildAt(strf("{}", Random::randu64()), newItem, at);
addChildAt(toString(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("{}", Random::randu64()), existingItem);
addChild(toString(Random::randu64()), existingItem);
updateSizeAndPosition();
return existingItem;

View File

@ -186,7 +186,7 @@ LuaCallbacks LuaBindings::makeWidgetCallbacks(Widget* parentWidget, GuiReaderPtr
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("{}", Random::randu64()));
String name = newChildName.value(toString(Random::randu64()));
WidgetPtr newChild = reader->makeSingle(name, newChildConfig);
widget->addChild(name, newChild);
}

View File

@ -360,7 +360,7 @@ WidgetConstructResult WidgetParser::radioGroupHandler(String const& name, Json c
common(button, btnConfig);
buttonGroup->addChild(strf("{}", button->buttonGroupId()), button);
buttonGroup->addChild(toString(button->buttonGroupId()), button);
} catch (MapException const& e) {
throw WidgetParserException(
strf("Malformed gui json, missing a required value in the map. {}", outputException(e, false)));
@ -749,7 +749,7 @@ WidgetConstructResult WidgetParser::stackHandler(String const& name, Json const&
auto widget = make_shared<Widget>();
constructImpl(widgetCfg, widget.get());
widget->determineSizeFromChildren();
stack->addChild(strf("{}", stack->numChildren()), widget);
stack->addChild(toString(stack->numChildren()), widget);
}
}