Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ include(third_party/hermes.cmake)
set(BUREAU_HERMES_FRAMEWORKS "${bureau_hermes_framework_dir}" CACHE INTERNAL "")
if(TARGET bureau_hermes)
add_library(bureau_js STATIC
src/js/host.cpp src/js/inspect.cpp src/js/ui.cpp src/js/view_bridge.cpp
src/js/awake_clock.cpp src/js/host.cpp src/js/inspect.cpp src/js/ui.cpp src/js/view_bridge.cpp
src/js/net/base64.cpp src/js/net/handshake.cpp src/js/net/http_request.cpp
src/js/net/websocket_frame.cpp)
if(WIN32)
Expand Down
14 changes: 13 additions & 1 deletion include/bureau/backends/quads.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// itself; see the backends for the one pipeline they need.
#pragma once

#include <cstddef>
#include <cstdint>
#include <vector>

Expand Down Expand Up @@ -47,9 +48,20 @@ struct Batches {
std::vector<Run> runs;
};

/** The most vertices a frame draws: 128 MB, which every backend's device
* takes in one buffer (Direct3D 11 guarantees no more). */
inline constexpr std::size_t kMaxVertices = (std::size_t{128} << 20) / sizeof(Vertex);

/** `list` for a target of `width` by `height` pixels, onto which it stretches
* when it was laid out for another size: a window leaving fullscreen draws the
* old list into its smaller frame until the UI lays out again. */
* old list into its smaller frame until the UI lays out again. A quad wholly
* outside its clip is left out, as the scissor would discard it, and past
* kMaxVertices the rest are: the topmost content goes rather than the frame. */
Batches batchesOf(const DisplayList& list, int width, int height);

/** The bytes a vertex buffer holding `held` bytes is made again at for
* `needed`: twice the larger, so a growing list reallocates rarely, and never
* past what kMaxVertices fill, which batchesOf never needs more than. */
std::uint64_t vertexBufferBytes(std::uint64_t needed, std::uint64_t held);

} // namespace bureau::backends
4 changes: 4 additions & 0 deletions include/bureau/bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ jsi::Value jsString(jsi::Runtime& runtime, const std::string& value);
/** A value from JavaScript as JSON, through its own JSON.stringify. */
nlohmann::json jsonOf(jsi::Runtime& runtime, const jsi::Value& value);

/** JSON's text for JavaScript. A byte that is not UTF-8 reads as U+FFFD, so
* one bad string costs a letter rather than the turn that carried it. */
std::string jsonText(const nlohmann::json& value);

void define(jsi::Runtime& runtime, jsi::Object& object, const char* name,
jsi::HostFunctionType body);

Expand Down
5 changes: 4 additions & 1 deletion include/bureau/ui.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ class Ui {
/** The looks, as JSON (tools/tokens.ts). */
std::string tokens;
/** A file the UI asks for by its path under the game's assets (`/fonts/…`,
* pictures); nothing when there is none. On the UI's thread. */
* pictures); nothing when there is none. On the UI's thread for the
* view's faces and pictures, and on a thread of the UI's own for what
* TypeScript reads (`assetText`, `assetBytes`), so it must be safe to
* call from both. */
std::function<std::optional<std::string>(const std::string& path)> readAsset;
/** The window, in points, and its device pixels per point. */
float width = 1280;
Expand Down
8 changes: 6 additions & 2 deletions kit/native_platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import type { KitPlatform, KitStorage } from "./platform.ts";

interface Native {
log(level: string, text: string): void;
assetText(path: string): string | null;
/** Reads off the interface's thread and calls `done` with the file, or
* null when there is none. */
assetText(path: string, done: (text: string | null) => void): void;
setClipboard?(text: string): void;
storageGet?(key: string): string | null;
storageSet?(key: string, value: string): void;
Expand Down Expand Up @@ -62,7 +64,9 @@ export const platform: KitPlatform = {
return Promise.resolve();
},
},
assets: { text: (path) => Promise.resolve(native.assetText(path)) },
assets: {
text: (path) => new Promise((resolve) => native.assetText(path, resolve)),
},
shell: { identity: undefined, isSteamDeck: false },
log: {
error: (message, ...details) =>
Expand Down
4 changes: 3 additions & 1 deletion src/backends/d3d11.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -195,11 +195,13 @@ void D3D11Backend::draw(ID3D11DeviceContext* context, const DisplayList& list,
Impl& d3d = *impl_;
if (d3d.pixelShader == nullptr || list.quads.empty()) return;
const auto batches = backends::batchesOf(list, width, height);
if (batches.vertices.empty()) return;
const UINT bytes =
static_cast<UINT>(batches.vertices.size() * sizeof(backends::Vertex));
if (bytes > d3d.vertexCapacity) {
release(d3d.vertices);
d3d.vertexCapacity = bytes * 2;
d3d.vertexCapacity =
static_cast<UINT>(backends::vertexBufferBytes(bytes, d3d.vertexCapacity));
D3D11_BUFFER_DESC description{};
description.ByteWidth = d3d.vertexCapacity;
description.Usage = D3D11_USAGE_DYNAMIC;
Expand Down
4 changes: 3 additions & 1 deletion src/backends/d3d12.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,13 @@ void D3D12Backend::draw(ID3D12GraphicsCommandList* commands, UINT slot,
Impl& d3d = *impl_;
if (d3d.pipeline == nullptr || list.quads.empty()) return;
const auto batches = backends::batchesOf(list, width, height);
if (batches.vertices.empty()) return;
const UINT64 bytes = batches.vertices.size() * sizeof(backends::Vertex);
HostBuffer& vertices = d3d.slots[slot].vertices;
if (bytes > vertices.capacity) {
const UINT64 size = backends::vertexBufferBytes(bytes, vertices.capacity);
d3d.destroyBuffer(vertices);
vertices = d3d.createBuffer(bytes * 2);
vertices = d3d.createBuffer(size);
}
std::memcpy(vertices.mapped, batches.vertices.data(), bytes);

Expand Down
1 change: 1 addition & 0 deletions src/backends/metal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ fragment float4 fs_main(VertexOut input [[stage_in]],
if (impl_->pipeline == nil || list.quads.empty()) return;
id<MTLRenderCommandEncoder> pass = (__bridge id<MTLRenderCommandEncoder>)encoder;
const auto batches = backends::batchesOf(list, width, height);
if (batches.vertices.empty()) return;
id<MTLBuffer> vertices = [impl_->device
newBufferWithBytes:batches.vertices.data()
length:batches.vertices.size() * sizeof(backends::Vertex)
Expand Down
1 change: 1 addition & 0 deletions src/backends/opengl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ void OpenGlBackend::draw(const DisplayList& list, int width, int height) {
if (list.quads.empty()) return;
Impl& gl = *impl_;
const auto batches = backends::batchesOf(list, width, height);
if (batches.vertices.empty()) return;

GLint program = 0, vertexArray = 0, arrayBuffer = 0, activeTexture = 0;
GLint texture[2] = {}, sampler[2] = {};
Expand Down
30 changes: 27 additions & 3 deletions src/backends/quads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,37 @@ Scissor scissorOf(const Clip& clip, const DisplayList& list, int width,
return {left, top, right - left, bottom - top};
}

/** Whether any of `corners` can reach a pixel of `clip`: a scissor keeps
* nothing of a quad off it, so a long list's rows out of sight cost nothing. */
bool reaches(const Vertex (&corners)[4], const Clip& clip) {
if (clip.width <= 0 || clip.height <= 0) return false;
float left = corners[0].x, right = corners[0].x;
float top = corners[0].y, bottom = corners[0].y;
for (const Vertex& corner : corners) {
left = std::min(left, corner.x);
right = std::max(right, corner.x);
top = std::min(top, corner.y);
bottom = std::max(bottom, corner.y);
}
const bool across = right > clip.x && left < clip.x + clip.width;
const bool down = bottom > clip.y && top < clip.y + clip.height;
return across && down;
}

} // namespace

std::uint64_t vertexBufferBytes(std::uint64_t needed, std::uint64_t held) {
const std::uint64_t most = kMaxVertices * sizeof(Vertex);
return std::min(std::max(needed, held) * 2, most);
}

Batches batchesOf(const DisplayList& list, int width, int height) {
Batches batches;
batches.vertices.reserve(list.quads.size() * 6);
batches.vertices.reserve(std::min(list.quads.size() * 6, kMaxVertices));
int page = -1;
int clip = -1;
for (const Quad& quad : list.quads) {
if (batches.vertices.size() + 6 > kMaxVertices) break;
const float mode = static_cast<float>(quad.mode);
const float stipple = static_cast<float>(quad.stipple);
const float smooth = quad.smooth ? 1.0f : 0.0f;
Expand All @@ -58,10 +81,11 @@ Batches batchesOf(const DisplayList& list, int width, int height) {
corner.y = quad.originY + x * sine + y * cosine;
}
}
const Clip& rect =
list.clips[std::min<size_t>(quad.clip, list.clips.size() - 1)];
if (!reaches(corners, rect)) continue;
const bool startsRun = quad.page != page || quad.clip != clip;
if (startsRun) {
const Clip& rect =
list.clips[std::min<size_t>(quad.clip, list.clips.size() - 1)];
batches.runs.push_back(
{static_cast<std::uint32_t>(batches.vertices.size()), 0, quad.page,
scissorOf(rect, list, width, height)});
Expand Down
5 changes: 4 additions & 1 deletion src/backends/vulkan.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -459,11 +459,14 @@ void VulkanBackend::draw(VkCommandBuffer commands, std::uint32_t slot,
Impl& vk = *impl_;
if (vk.pipeline == VK_NULL_HANDLE || list.quads.empty()) return;
const auto batches = backends::batchesOf(list, width, height);
if (batches.vertices.empty()) return;
const VkDeviceSize bytes = batches.vertices.size() * sizeof(backends::Vertex);
HostBuffer& vertices = vk.slots[slot].vertices;
if (bytes > vertices.capacity) {
const VkDeviceSize size =
backends::vertexBufferBytes(bytes, vertices.capacity);
vk.destroyBuffer(vertices);
vertices = vk.createBuffer(bytes * 2, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
vertices = vk.createBuffer(size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
}
std::memcpy(vertices.mapped, batches.vertices.data(), bytes);

Expand Down
66 changes: 66 additions & 0 deletions src/js/awake_clock.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// LEAN_AND_MEAN and NOMINMAX before any include: <windows.h> pulls in less
// and leaves std::min and std::max alone.
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#endif

#include "awake_clock.h"

#include <chrono>

#if defined(__APPLE__)
#include <time.h>
#endif

namespace bureau::js {

#if defined(__APPLE__)

std::int64_t awakeNanoseconds() {
return static_cast<std::int64_t>(clock_gettime_nsec_np(CLOCK_UPTIME_RAW));
}

#elif defined(_WIN32)

namespace {

using UnbiasedTime = VOID(WINAPI*)(PULONGLONG);

/** Windows 10's precise unbiased interrupt time, in 100 ns units, leaves out
* sleep and hibernation; looked up rather than linked, since only mincore.lib
* names it. */
UnbiasedTime unbiasedTime() {
const HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
if (kernel == nullptr) return nullptr;
return reinterpret_cast<UnbiasedTime>(
GetProcAddress(kernel, "QueryUnbiasedInterruptTimePrecise"));
}

} // namespace

std::int64_t awakeNanoseconds() {
static const UnbiasedTime read = unbiasedTime();
if (read == nullptr) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
ULONGLONG hundreds = 0;
read(&hundreds);
return static_cast<std::int64_t>(hundreds) * 100;
}

#else

// CLOCK_MONOTONIC, which stops while Linux and Android suspend.
std::int64_t awakeNanoseconds() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}

#endif

} // namespace bureau::js
15 changes: 15 additions & 0 deletions src/js/awake_clock.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once

#include <cstdint>

namespace bureau::js {

/**
* Nanoseconds the machine has spent awake, from an arbitrary start: the clock
* behind performance.now(). It stops while the machine sleeps, so a game can
* tell a sleep (the wall clock ran on alone) from a thread that stalled.
* std::chrono::steady_clock runs on through sleep on macOS and Windows.
*/
std::int64_t awakeNanoseconds();

} // namespace bureau::js
Loading
Loading