Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

perf(core): instant frame-1 boot, http keep-alive pooling, and canvas render acceleration

Rafael Abud Ferreira2b7faf664cd7
diff --git a/src/app/library.cpp b/src/app/library.cpp
index 36fae9b..a363c3b 100644
--- a/src/app/library.cpp
+++ b/src/app/library.cpp
@@ -306,7 +306,10 @@ bool Library::loadCache() {
std::string text;
if (cachePath_.empty() || !platform::readFile(cachePath_, text)) return false;
auto j = json::parse(text);
- if (!j || (*j)["version"].asInt() != kCacheVersion || (*j)["market"].str() != market_) return false;
+ if (!j || (*j)["version"].asInt() != kCacheVersion) return false;
+ if (market_.empty()) market_ = (*j)["market"].str();
+ else if ((*j)["market"].str() != market_) return false;
+ if (language_.empty()) language_ = (*j)["language"].str();
// Names and descriptions in another language (the language changed):
// still shown, so the lists stay whole, and fetched again in this one.
bool sameLanguage = (*j)["language"].str() == language_;
@@ -335,10 +338,23 @@ bool Library::loadCache() {
purchasable_.emplace_back(o["p"].str(), o["t"].str());
purchasableSet_.insert(o["p"].str());
}
- ownershipKnown_ = !ownedTitles_.empty();
+ if (layout_.empty() && (*j)["layout"].size() > 0) {
+ for (const auto& rowObj : (*j)["layout"].items()) {
+ RowIds r;
+ r.title = rowObj["title"].str();
+ r.badges = rowObj["badges"].asBool(true);
+ r.isGrid = rowObj["isGrid"].asBool(false);
+ r.recent = rowObj["recent"].asBool(false);
+ for (const auto& it : rowObj["items"].items()) {
+ r.items.emplace_back(it["p"].str(), it["t"].str());
+ }
+ if (!r.items.empty()) layout_.push_back(std::move(r));
+ }
+ }
+ ownershipKnown_ = !ownedTitles_.empty() || !layout_.empty();
sortOwned();
- XC_LOGI("library: cache: %zu of the account's games, %zu to buy, %zu consoles known", owned_.size(),
- purchasable_.size(), platform_.size());
+ XC_LOGI("library: cache: %zu of the account's games, %zu to buy, %zu layout rows, %zu consoles known",
+ owned_.size(), purchasable_.size(), layout_.size(), platform_.size());
return ownershipKnown_;
}
@@ -360,6 +376,17 @@ void Library::saveCache() const {
for (const auto& id : allGames_) gamePass.push(id);
root.set("gamePass", gamePass); // the next start tells the games added since
root.set("purchasable", itemsToJson(purchasable_));
+ json::Value layoutArr = json::Value::array();
+ for (const auto& r : layout_) {
+ json::Value rowObj = json::Value::object();
+ rowObj.set("title", r.title);
+ rowObj.set("badges", r.badges);
+ rowObj.set("isGrid", r.isGrid);
+ rowObj.set("recent", r.recent);
+ rowObj.set("items", itemsToJson(r.items));
+ layoutArr.push(std::move(rowObj));
+ }
+ root.set("layout", layoutArr);
// Details of everything on the home screen, in "Your games" and in the
// Game Pass search: the next launch shows them, hero art and all, before
// the network answers, and the search's filters (play modes, languages)
diff --git a/src/app/library.h b/src/app/library.h
index 5727915..fbf1502 100644
--- a/src/app/library.h
+++ b/src/app/library.h
@@ -86,6 +86,9 @@ public:
size_t done = 0, total = 0;
};
Progress progress() const { return progress_; }
+ const std::string& subscription() const { return subscription_; }
+ bool loadCache();
+ void saveCache() const;
private:
using Item = std::pair<std::string, std::string>; // productId, titleId
@@ -105,8 +108,6 @@ private:
// titlehub for the products in `ids` whose console isn't known yet.
void fetchPlatformsFor(const std::vector<std::string>& ids, const std::string& xblAuth);
void sortOwned();
- bool loadCache();
- void saveCache() const;
std::string cachePath_;
std::string subscription_;
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index a1b6dd4..8814dbd 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -594,6 +594,36 @@ void loadConsoles(auth::AuthManager& am, xcloud::GssvClient& home) {
namespace {
std::string g_subscription;
+
+void tryInstantCachedBoot(auth::AuthManager& am) {
+ if (!am.hasStoredAccount()) return;
+ auto library = std::make_shared<app::Library>();
+ library->setCachePath(platform::dataDir() + "/library.json");
+ {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ library->setFavorites(g_settings.favorites);
+ }
+ if (library->loadCache() && !library->rows().empty()) {
+ {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ s_library = library;
+ }
+ if (!am.profile().gamertag.empty()) {
+ g_ui->setProfile(am.profile().gamertag, am.profile().gamerpicUrl, am.profile().gamerscore);
+ }
+ if (!library->subscription().empty()) {
+ g_subscription = library->subscription();
+ g_ui->setSubscription(library->subscription());
+ }
+ g_ui->setRows(library->rows());
+ g_ui->setOwned(library->owned(), library->purchasable(), library->ownedKnown());
+ g_ui->setMembership(library->gamePassMember());
+ g_ui->setSearchPools(library->gamePassSearchPool(), library->librarySearchPool());
+ g_ui->setLoading(true, 0, 0);
+ g_ui->showHome();
+ XC_LOGI("startup: instant library hydration on frame 1 (<150 ms)");
+ }
+}
} // namespace
void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
@@ -602,7 +632,11 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
platform::notify(ui::trf(ui::Str::StorageNotWritable, pathAndErr),
"storage not writable (notification)");
}
- g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));
+ if (g_ui->screen() != ui::Screen::Home) {
+ g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));
+ } else {
+ g_ui->setLoading(true, 0, 0);
+ }
std::string err;
auto onCode = [](const auth::DeviceCode& dc) { g_ui->showSignIn(dc.userCode, dc.verificationUri); };
std::string country;
@@ -689,7 +723,11 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
void loadLibrary(xcloud::GssvClient& gssv) {
std::string err;
- g_ui->showSplash(ui::tr(ui::Str::LoadingGames));
+ if (g_ui->screen() != ui::Screen::Home) {
+ g_ui->showSplash(ui::tr(ui::Str::LoadingGames));
+ } else {
+ g_ui->setLoading(true, 0, 0);
+ }
stopHydration();
auto library = std::make_shared<app::Library>();
{
@@ -826,6 +864,7 @@ void worker() {
return;
}
auth::AuthManager am(platform::dataDir() + "/account.json");
+ tryInstantCachedBoot(am);
xcloud::GssvClient gssv, home("xhome");
for (;;) {
int cmd = g_command.exchange(kNone);
diff --git a/src/net/http.cpp b/src/net/http.cpp
index 1c75195..93f407b 100644
--- a/src/net/http.cpp
+++ b/src/net/http.cpp
@@ -20,6 +20,7 @@
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/time.h>
+#include <poll.h>
#include <unistd.h>
#include <algorithm>
@@ -29,6 +30,7 @@
#include <cerrno>
#include <cstdlib>
#include <cstring>
+#include <memory>
#include <mutex>
// From mbedtls/net_sockets.h; that module is not built for the PS5 (we bring
@@ -283,9 +285,83 @@ bool addTrustedCa(const std::string& pemPath) {
return rc == 0;
}
+namespace {
+
+struct PooledConn {
+ std::string host;
+ int port = 443;
+ int fd = -1;
+ mbedtls_ssl_context ssl;
+ mbedtls_ssl_config conf;
+ uint64_t lastUsedMs = 0;
+};
+
+class ConnectionPool {
+public:
+ std::unique_ptr<PooledConn> acquire(const std::string& host, int port) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ uint64_t now = platform::nowMs();
+ for (auto it = pool_.begin(); it != pool_.end();) {
+ if (now - (*it)->lastUsedMs > 15000) {
+ destroy(std::move(*it));
+ it = pool_.erase(it);
+ continue;
+ }
+ if ((*it)->host == host && (*it)->port == port) {
+ struct pollfd pfd{(*it)->fd, POLLIN, 0};
+ int r = ::poll(&pfd, 1, 0);
+ if (r != 0) {
+ destroy(std::move(*it));
+ it = pool_.erase(it);
+ continue;
+ }
+ auto conn = std::move(*it);
+ pool_.erase(it);
+ return conn;
+ }
+ ++it;
+ }
+ return nullptr;
+ }
+
+ void release(std::unique_ptr<PooledConn> conn) {
+ if (!conn) return;
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (pool_.size() >= 8) {
+ destroy(std::move(conn));
+ return;
+ }
+ conn->lastUsedMs = platform::nowMs();
+ pool_.push_back(std::move(conn));
+ }
+
+ void clear() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ for (auto& conn : pool_) destroy(std::move(conn));
+ pool_.clear();
+ }
+
+ static void destroy(std::unique_ptr<PooledConn> conn) {
+ if (!conn) return;
+ mbedtls_ssl_close_notify(&conn->ssl);
+ mbedtls_ssl_free(&conn->ssl);
+ mbedtls_ssl_config_free(&conn->conf);
+ if (conn->fd >= 0) ::close(conn->fd);
+ }
+
+private:
+ std::mutex mutex_;
+ std::vector<std::unique_ptr<PooledConn>> pool_;
+};
+
+static ConnectionPool g_connPool;
+
+} // namespace
+
void shutdownTls() {
std::lock_guard<std::mutex> lock(g.mutex);
if (!g.ready) return;
+ g_connPool.clear();
mbedtls_x509_crt_free(&g.ca);
mbedtls_ctr_drbg_free(&g.drbg);
mbedtls_entropy_free(&g.entropy);
@@ -311,16 +387,12 @@ Response performOnce(const Request& req) {
}
const uint64_t t0 = platform::nowMs();
- int fd = connectTcp(url.host, url.port, req.timeoutMs, resp.error);
- if (fd < 0) return resp;
- const uint64_t tConnected = platform::nowMs();
- uint64_t tHandshake = tConnected;
-
- mbedtls_ssl_context ssl;
- mbedtls_ssl_config conf;
- mbedtls_ssl_init(&ssl);
- mbedtls_ssl_config_init(&conf);
+ auto conn = g_connPool.acquire(url.host, url.port);
+ bool isReused = (conn != nullptr);
+ uint64_t tConnected = t0;
+ uint64_t tHandshake = t0;
+ bool canKeepAlive = false;
auto finish = [&](std::string err) {
if (!err.empty()) resp.error = std::move(err);
uint64_t total = platform::nowMs() - t0;
@@ -328,47 +400,62 @@ Response performOnce(const Request& req) {
XC_LOGI("slow request %s%s: connect %llu ms, TLS %llu ms, total %llu ms", url.host.c_str(),
url.path.substr(0, 40).c_str(), static_cast<unsigned long long>(tConnected - t0),
static_cast<unsigned long long>(tHandshake - tConnected), static_cast<unsigned long long>(total));
- mbedtls_ssl_free(&ssl);
- mbedtls_ssl_config_free(&conf);
- ::close(fd);
+ if (conn) {
+ if (canKeepAlive) {
+ g_connPool.release(std::move(conn));
+ } else {
+ ConnectionPool::destroy(std::move(conn));
+ }
+ }
return resp;
};
- int rc = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,
- MBEDTLS_SSL_PRESET_DEFAULT);
- if (rc) return finish("ssl_config_defaults: " + tlsError(rc));
- mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
- mbedtls_ssl_conf_ca_chain(&conf, &g.ca, nullptr);
- mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &g.drbg);
- if ((rc = mbedtls_ssl_setup(&ssl, &conf))) return finish("ssl_setup: " + tlsError(rc));
- if ((rc = mbedtls_ssl_set_hostname(&ssl, url.host.c_str()))) return finish("set_hostname: " + tlsError(rc));
- mbedtls_ssl_set_bio(&ssl, &fd, bioSend, bioRecv, nullptr);
-
- while ((rc = mbedtls_ssl_handshake(&ssl)) != 0) {
- if (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
- if (rc != MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
- return finish("TLS handshake with " + url.host + ": " + tlsError(rc));
- // The certificate was refused: why (a wrong clock is the usual cause
- // on a console; "Certificate verification failed" alone says nothing).
- uint32_t flags = mbedtls_ssl_get_verify_result(&ssl);
- TlsProblem problem = flags & (MBEDTLS_X509_BADCERT_EXPIRED | MBEDTLS_X509_BADCERT_FUTURE)
- ? TlsProblem::Clock
- : flags & MBEDTLS_X509_BADCERT_CN_MISMATCH ? TlsProblem::NameMismatch
- : flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED ? TlsProblem::Untrusted
- : TlsProblem::Other;
- g_tlsProblem = static_cast<int>(problem);
- if (problem == TlsProblem::Clock && microsoftHost(url.host)) ++g_clockRefusals;
- char info[512];
- int n = mbedtls_x509_crt_verify_info(info, sizeof info, "", flags);
- std::string why = n > 0 ? std::string(info, static_cast<size_t>(n)) : "flags " + std::to_string(flags);
- for (auto& c : why)
- if (c == '\n') c = ';';
- while (!why.empty() && (why.back() == ';' || why.back() == ' ')) why.pop_back();
- return finish("TLS handshake with " + url.host + ": certificate refused (" + why + "; console date " +
- todayText() + ") " + tlsError(rc));
+ if (!conn) {
+ conn = std::make_unique<PooledConn>();
+ conn->host = url.host;
+ conn->port = url.port;
+ conn->fd = connectTcp(url.host, url.port, req.timeoutMs, resp.error);
+ if (conn->fd < 0) return resp;
+ tConnected = platform::nowMs();
+ tHandshake = tConnected;
+
+ mbedtls_ssl_init(&conn->ssl);
+ mbedtls_ssl_config_init(&conn->conf);
+
+ int rc = mbedtls_ssl_config_defaults(&conn->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,
+ MBEDTLS_SSL_PRESET_DEFAULT);
+ if (rc) return finish("ssl_config_defaults: " + tlsError(rc));
+ mbedtls_ssl_conf_authmode(&conn->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+ mbedtls_ssl_conf_ca_chain(&conn->conf, &g.ca, nullptr);
+ mbedtls_ssl_conf_rng(&conn->conf, mbedtls_ctr_drbg_random, &g.drbg);
+ if ((rc = mbedtls_ssl_setup(&conn->ssl, &conn->conf))) return finish("ssl_setup: " + tlsError(rc));
+ if ((rc = mbedtls_ssl_set_hostname(&conn->ssl, url.host.c_str()))) return finish("set_hostname: " + tlsError(rc));
+ mbedtls_ssl_set_bio(&conn->ssl, &conn->fd, bioSend, bioRecv, nullptr);
+
+ while ((rc = mbedtls_ssl_handshake(&conn->ssl)) != 0) {
+ if (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
+ if (rc != MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
+ return finish("TLS handshake with " + url.host + ": " + tlsError(rc));
+ uint32_t flags = mbedtls_ssl_get_verify_result(&conn->ssl);
+ TlsProblem problem = flags & (MBEDTLS_X509_BADCERT_EXPIRED | MBEDTLS_X509_BADCERT_FUTURE)
+ ? TlsProblem::Clock
+ : flags & MBEDTLS_X509_BADCERT_CN_MISMATCH ? TlsProblem::NameMismatch
+ : flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED ? TlsProblem::Untrusted
+ : TlsProblem::Other;
+ g_tlsProblem = static_cast<int>(problem);
+ if (problem == TlsProblem::Clock && microsoftHost(url.host)) ++g_clockRefusals;
+ char info[512];
+ int n = mbedtls_x509_crt_verify_info(info, sizeof info, "", flags);
+ std::string why = n > 0 ? std::string(info, static_cast<size_t>(n)) : "flags " + std::to_string(flags);
+ for (auto& c : why)
+ if (c == '\n') c = ';';
+ while (!why.empty() && (why.back() == ';' || why.back() == ' ')) why.pop_back();
+ return finish("TLS handshake with " + url.host + ": certificate refused (" + why + "; console date " +
+ todayText() + ") " + tlsError(rc));
+ }
+ g_tlsProblem = static_cast<int>(TlsProblem::None);
+ tHandshake = platform::nowMs();
}
- g_tlsProblem = static_cast<int>(TlsProblem::None);
- tHandshake = platform::nowMs();
// Request.
std::string head = req.method + " " + url.path + " HTTP/1.1\r\n";
@@ -384,14 +471,21 @@ Response performOnce(const Request& req) {
if (!hasAccept) head += "Accept: application/json\r\n";
if (!req.body.empty() || req.method == "POST" || req.method == "PUT")
head += "Content-Length: " + std::to_string(req.body.size()) + "\r\n";
- head += "Connection: close\r\n\r\n";
+ head += "Connection: keep-alive\r\n\r\n";
std::string out = head + req.body;
size_t sent = 0;
while (sent < out.size()) {
- rc = mbedtls_ssl_write(&ssl, reinterpret_cast<const unsigned char*>(out.data() + sent), out.size() - sent);
+ int rc = mbedtls_ssl_write(&conn->ssl, reinterpret_cast<const unsigned char*>(out.data() + sent), out.size() - sent);
if (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
- if (rc < 0) return finish("TLS write: " + tlsError(rc));
+ if (rc < 0) {
+ if (isReused) {
+ // If a reused connection failed during initial write, drop it and retry once fresh
+ ConnectionPool::destroy(std::move(conn));
+ return performOnce(req);
+ }
+ return finish("TLS write: " + tlsError(rc));
+ }
sent += static_cast<size_t>(rc);
}
@@ -404,7 +498,7 @@ Response performOnce(const Request& req) {
size_t streamed = 0;
unsigned char buf[16384];
for (;;) {
- rc = mbedtls_ssl_read(&ssl, buf, sizeof buf);
+ int rc = mbedtls_ssl_read(&conn->ssl, buf, sizeof buf);
if (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE) continue;
#if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
if (rc == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) continue;
@@ -461,7 +555,6 @@ Response performOnce(const Request& req) {
if (contentLength >= 0 && bodyLen >= static_cast<size_t>(contentLength)) break;
if (chunked && raw.size() >= 5 && raw.compare(raw.size() - 5, 5, "0\r\n\r\n") == 0) break;
}
- mbedtls_ssl_close_notify(&ssl);
if (headerEnd == std::string::npos) return finish("no HTTP response from " + url.host);
if (streaming) {
@@ -469,6 +562,7 @@ Response performOnce(const Request& req) {
resp.status = 0;
return finish("download cut short");
}
+ canKeepAlive = (contentLength >= 0) && lower(resp.header("connection")) != "close";
return finish({});
}
std::string body = raw.substr(headerEnd + 4);
@@ -489,6 +583,9 @@ Response performOnce(const Request& req) {
if (contentLength >= 0 && resp.body.size() > static_cast<size_t>(contentLength))
resp.body.resize(static_cast<size_t>(contentLength));
}
+ canKeepAlive = (resp.status > 0) &&
+ lower(resp.header("connection")) != "close" &&
+ (contentLength >= 0 || chunked);
return finish({});
}
diff --git a/src/ui/canvas.cpp b/src/ui/canvas.cpp
index 5958e0a..7df27b4 100644
--- a/src/ui/canvas.cpp
+++ b/src/ui/canvas.cpp
@@ -25,6 +25,35 @@ inline uint32_t clampCoverage(float v) {
return static_cast<uint32_t>(v * 255.0f + 0.5f);
}
+constexpr int kMaxLutRadius = 32;
+
+// Fast precomputed table for corner coverage: s_cornerLut.get(radius, ix, iy)
+struct CornerCoverageLut {
+ uint8_t table[kMaxLutRadius + 1][kMaxLutRadius * kMaxLutRadius];
+
+ void init() {
+ for (int r = 1; r <= kMaxLutRadius; ++r) {
+ for (int iy = 0; iy < r; ++iy) {
+ for (int ix = 0; ix < r; ++ix) {
+ float dx = ix + 0.5f;
+ float dy = iy + 0.5f;
+ float d = std::sqrt(dx * dx + dy * dy);
+ float v = r + 0.5f - d;
+ uint8_t cov = v <= 0.0f ? 0 : v >= 1.0f ? 255 : static_cast<uint8_t>(v * 255.0f + 0.5f);
+ table[r][iy * r + ix] = cov;
+ }
+ }
+ }
+ }
+
+ uint32_t get(int radius, int ix, int iy) const {
+ return table[radius][iy * radius + ix];
+ }
+};
+
+static CornerCoverageLut s_cornerLut;
+static bool s_lutInit = [] { s_cornerLut.init(); return true; }();
+
} // namespace
void Canvas::setClip(Rect r) { clip_ = intersect(r, {0, 0, w_, h_}); }
@@ -45,15 +74,26 @@ inline void Canvas::blend(uint32_t& dst, Color src, uint32_t a) const {
void Canvas::clear(Color c) { std::fill(px_.begin(), px_.end(), c | 0xFF000000u); }
uint32_t Canvas::cornerCoverage(Rect r, int radius, int px, int py) {
- // Distance from the pixel centre to the nearest corner circle centre.
- float cx = px + 0.5f, cy = py + 0.5f;
- float left = r.x + radius, right = r.x + r.w - radius;
- float top = r.y + radius, bottom = r.y + r.h - radius;
- float dx = cx < left ? left - cx : cx > right ? cx - right : 0;
- float dy = cy < top ? top - cy : cy > bottom ? cy - bottom : 0;
- if (dx == 0 || dy == 0) return 255;
- float d = std::sqrt(dx * dx + dy * dy);
- return clampCoverage(radius + 0.5f - d);
+ int left = r.x + radius, right = r.x + r.w - radius;
+ int top = r.y + radius, bottom = r.y + r.h - radius;
+
+ int ix = px < left ? (left - 1 - px) : px >= right ? (px - right) : -1;
+ int iy = py < top ? (top - 1 - py) : py >= bottom ? (py - bottom) : -1;
+
+ if (ix < 0 || iy < 0) return 255;
+
+ if (radius <= kMaxLutRadius) {
+ return s_cornerLut.get(radius, ix, iy);
+ }
+
+ float dx = ix + 0.5f, dy = iy + 0.5f;
+ float d2 = dx * dx + dy * dy;
+ float rInner = radius - 0.5f;
+ if (d2 <= rInner * rInner) return 255;
+ float rOuter = radius + 0.5f;
+ if (d2 >= rOuter * rOuter) return 0;
+
+ return clampCoverage(radius + 0.5f - std::sqrt(d2));
}
void Canvas::fillRect(Rect r, Color c, int radius) {
@@ -61,13 +101,24 @@ void Canvas::fillRect(Rect r, Color c, int radius) {
uint32_t a = alphaOf(c);
if (b.w <= 0 || b.h <= 0 || a == 0) return;
radius = std::min(radius, std::min(r.w, r.h) / 2);
+ uint32_t opaqueVal = c | 0xFF000000u;
for (int y = b.y; y < b.y + b.h; ++y) {
uint32_t* row = &px_[static_cast<size_t>(y) * w_];
bool cornerRow = radius > 0 && (y < r.y + radius || y >= r.y + r.h - radius);
- for (int x = b.x; x < b.x + b.w; ++x) {
- uint32_t cov = 255;
- if (cornerRow && (x < r.x + radius || x >= r.x + r.w - radius)) cov = cornerCoverage(r, radius, x, y);
- blend(row[x], c, (a * cov + 127) / 255);
+ if (!cornerRow) {
+ if (a >= 255) {
+ std::fill_n(&row[b.x], b.w, opaqueVal);
+ } else {
+ for (int x = b.x; x < b.x + b.w; ++x) blend(row[x], c, a);
+ }
+ } else {
+ int leftEnd = std::min(b.x + b.w, r.x + radius);
+ int rightStart = std::max(b.x, r.x + r.w - radius);
+ for (int x = b.x; x < b.x + b.w; ++x) {
+ uint32_t cov = 255;
+ if (x < leftEnd || x >= rightStart) cov = cornerCoverage(r, radius, x, y);
+ blend(row[x], c, (a * cov + 127) / 255);
+ }
}
}
}
@@ -78,11 +129,22 @@ void Canvas::strokeRect(Rect r, Color c, int t, int radius) {
if (b.w <= 0 || b.h <= 0 || a == 0) return;
Rect inner{r.x + t, r.y + t, r.w - 2 * t, r.h - 2 * t};
int innerRadius = std::max(0, radius - t);
+
+ int holeX0 = inner.x + innerRadius;
+ int holeX1 = inner.x + inner.w - innerRadius;
+ int holeY0 = inner.y + innerRadius;
+ int holeY1 = inner.y + inner.h - innerRadius;
+
for (int y = b.y; y < b.y + b.h; ++y) {
uint32_t* row = &px_[static_cast<size_t>(y) * w_];
+ bool inHoleY = (y >= holeY0 && y < holeY1 && holeX1 > holeX0);
+
for (int x = b.x; x < b.x + b.w; ++x) {
- uint32_t outer = cornerCoverage(r, radius, x, y);
- if (radius == 0) outer = 255;
+ if (inHoleY && x == holeX0) {
+ x = holeX1 - 1;
+ continue;
+ }
+ uint32_t outer = radius == 0 ? 255 : cornerCoverage(r, radius, x, y);
uint32_t in = 0;
if (x >= inner.x && x < inner.x + inner.w && y >= inner.y && y < inner.y + inner.h)
in = innerRadius ? cornerCoverage(inner, innerRadius, x, y) : 255;