Merge branch 'perf/frame'

# Conflicts:
#	runtime/include/bozo/host/free_host.h
This commit is contained in:
Thomas Martin committed 2026-11-05 00:05:22 +01:00
commit 8575559c77
11 files changed
+311 -82

No files matched your search

+40 -12
View File
@@ -149,6 +149,8 @@ namespace bozo::ee
{
ctx->pc = pc;
++stops;
if (stopJump_)
__builtin_longjmp(stopJump_, 1);
throw StopGuest{};
}
@@ -618,6 +620,27 @@ namespace bozo::ee
host_.fault(*this, ctx, std::format("no code at 0x{:x}", pc));
}
// Its own function, not inlined: after the jump back nothing of runFrame's locals is relied on (only what was set
// before the __builtin_setjmp and not changed since: this and ctx).
__attribute__((noinline)) bool Dispatcher::enterCatchingStops(R5900Context *ctx)
{
void *buf[5];
if (__builtin_setjmp(buf))
{
stopJump_ = nullptr;
return false;
}
stopJump_ = buf;
struct Clear // an exception passing through (a host ending the run) leaves no jump target behind
{
void **&p;
~Clear() { p = nullptr; }
} clear{stopJump_};
updateLimit(ctx);
enter(ctx);
return ctx->pc == 0;
}
void Dispatcher::runFrame(Thread &t, Frame &f)
{
current_ = &t;
@@ -629,17 +652,21 @@ namespace bozo::ee
inGuest_ = true;
lastHandlerEnded_ = false;
bool ended = false;
try
{
updateLimit(ctx);
// Guest code runs until it stops or the bottom function returns: then into a function whose frame is gone
// (the dispatcher goes on there, at ctx->pc, as after any stop), or to 0 (the thread or handler ends).
enter(ctx);
ended = ctx->pc == 0;
}
catch (const StopGuest &)
{
}
if (jumpStops)
ended = enterCatchingStops(ctx);
else
try
{
updateLimit(ctx);
// Guest code runs until it stops or the bottom function returns: then into a function whose frame is
// gone (the dispatcher goes on there, at ctx->pc, as after any stop), or to 0 (the thread or handler
// ends).
enter(ctx);
ended = ctx->pc == 0;
}
catch (const StopGuest &)
{
}
inGuest_ = false;
ctx->noStop = 0; // a stop or a return to the dispatcher ends every inner call (their return stack is gone)
ctx->inPlace = 0;
@@ -648,7 +675,8 @@ namespace bozo::ee
checkpoints_ = ctx->checkpoints;
f.status = rt_.cop0Status;
f.ran = true;
toWords(f.ctx, f.status, f.last);
if (keepStopWords)
toWords(f.ctx, f.status, f.last);
lastThread_ = t.id;
lastDepth_ = t.depth();
current_ = nullptr;
+25 -8
View File
@@ -1,6 +1,8 @@
// BozoEngine's EE kernel. See bozo/ee/kernel.h and docs/specs/kernel.md.
#include "bozo/ee/kernel.h"
#include <bit>
#include <algorithm>
namespace bozo::ee
@@ -60,11 +62,23 @@ namespace bozo::ee
// The ready queues hold the ready threads; the running thread is outside them (calllog: a thread that gives way
// goes to the tail of its queue, behind the threads already there).
void Kernel::noteQueue(uint32_t p)
{
const uint64_t bit = 1ull << (p & 63u);
if (ready_[p].empty())
readyMask_[p >> 6] &= ~bit;
else
readyMask_[p >> 6] |= bit;
}
int32_t Kernel::firstReady() const
{
for (const auto &q : ready_)
if (!q.empty())
return q.front();
// The lowest non-empty queue, by the mask of non-empty queues (the dispatcher asks at every pick, and at every
// transfer: scanning 128 queues was ~2.5% of a 1P match's game thread).
if (readyMask_[0])
return ready_[std::countr_zero(readyMask_[0])].front();
if (readyMask_[1])
return ready_[64 + std::countr_zero(readyMask_[1])].front();
return 0;
}
@@ -86,11 +100,10 @@ namespace bozo::ee
auto it = threads_.find(running_);
if (running_ <= 0 || it == threads_.end() || it->second->state != ThreadState::Running)
return false;
const uint32_t p = it->second->priority % kPriorities;
for (uint32_t q = 0; q <= p; ++q)
if (!ready_[q].empty())
return true;
return false;
const uint32_t p = it->second->priority % kPriorities; // any non-empty queue at p or below
if (p < 64)
return (readyMask_[0] & (p == 63 ? ~0ull : (2ull << p) - 1u)) != 0;
return readyMask_[0] != 0 || (readyMask_[1] & (p == 127 ? ~0ull : (2ull << (p - 64)) - 1u)) != 0;
}
void Kernel::runOrder(std::vector<int32_t> &out) const
@@ -134,12 +147,14 @@ namespace bozo::ee
{
t.state = ThreadState::Ready;
ready_[t.priority % kPriorities].push_back(t.id);
noteQueue(t.priority % kPriorities);
}
void Kernel::removeFromQueue(Thread &t)
{
auto &q = ready_[t.priority % kPriorities];
q.erase(std::remove(q.begin(), q.end(), t.id), q.end());
noteQueue(t.priority % kPriorities);
}
void Kernel::deschedule(bool toTail)
@@ -156,6 +171,7 @@ namespace bozo::ee
q.push_back(t->id);
else
q.push_front(t->id);
noteQueue(t->priority % kPriorities);
}
}
running_ = 0;
@@ -275,6 +291,7 @@ namespace bozo::ee
removeFromQueue(*t);
t->priority = priority;
ready_[priority % kPriorities].push_back(t->id);
noteQueue(priority % kPriorities);
}
else
t->priority = priority;
+9 -1
View File
@@ -30,6 +30,10 @@ namespace bozo::host
std::string &error)
{
d_ = &d;
// Stops jump back to the dispatcher (nothing on the way holds anything to destroy: dispatcher.h), and no frame
// keeps the context words only the call-log host compares.
d.jumpStops = true;
d.keepStopWords = false;
d.kernel().setObserver(this);
d.runtime().port = this;
libs_.attach(d);
@@ -97,6 +101,8 @@ namespace bozo::host
if (const ee::KernelCall k = ee::kernelCallByName(name); k != ee::KernelCall::None)
{
d.bindKernelCall(a, k);
if (name.find("FlushCache") != std::string::npos)
flushCacheAt_.insert(a);
continue;
}
// A library BozoEngine implements; anything else (an override address the port registered nothing at, a
@@ -119,6 +125,8 @@ namespace bozo::host
h.elfName = "SCUS_971.01";
writing_ = writer_.open(opt_.out, h);
}
// The draw lists' digest is the record's `draws`: not computed when no record is written.
render::Renderer::instance().setDrawDigest(writing_);
return true;
}
@@ -293,7 +301,7 @@ namespace bozo::host
void FreeHost::kernelCallEnd(ee::Dispatcher &, R5900Context *, uint32_t target, bool)
{
++stats_.kernelCalls;
if (auto n = names_.find(target); n != names_.end() && n->second.find("FlushCache") != std::string::npos)
if (flushCacheAt_.count(target))
libs_.io.flushCache();
}
+14
View File
@@ -203,6 +203,16 @@ namespace bozo::ee
// Pinned mode (kernel.md section 4): asynchronous events are taken where the host says (the reference's
// points), not when the EE clock reaches them; everything else is decided as in free mode.
bool pinned = false;
// How a stop leaves guest code. Off: by throwing StopGuest, which unwinds every C++ frame between the stop and
// the dispatcher (each one's destructors run). On: by a jump straight back to the dispatcher (__builtin_longjmp),
// no frame unwound: a host may set it only when nothing between holds anything to destroy (the generated code,
// the runtime's entries and its own out-call paths; a port's overrides never see a stop, it is deferred there:
// kernel.md section 3b). The free host does: an exception's unwinding cost ~20 us a stop (the 1P match's
// jumps through registers, dbsTraverse's table, stop a few hundred times a second).
bool jumpStops = false;
// Whether each frame keeps the context it stopped with (Frame::last, the CTX record's words: calllog.md 4.4).
// Only the call-log host reads them.
bool keepStopWords = true;
// Statistics.
uint64_t dispatches = 0, stops = 0, handlersRun = 0, jumps = 0;
@@ -214,6 +224,9 @@ namespace bozo::ee
bool kernelCall(KernelCall call, R5900Context *ctx);
Thread *choose();
void runFrame(Thread &t, Frame &f);
// Runs guest code at ctx->pc (enter) with a stop's jump target set (jumpStops): true when the bottom function
// returned, false when guest code stopped.
bool enterCatchingStops(R5900Context *ctx);
// Runs guest code at ctx->pc until the bottom function returns.
void enter(R5900Context *ctx);
bool mustStop(const R5900Context *ctx, uint64_t cycle);
@@ -245,5 +258,6 @@ namespace bozo::ee
bool started_ = false;
uint32_t outcallDepth_ = 0;
uint32_t deferredPc_ = 0;
void **stopJump_ = nullptr; // enterCatchingStops' __builtin_setjmp buffer while guest code runs (jumpStops)
};
}
+2
View File
@@ -332,6 +332,8 @@ namespace bozo::ee
std::map<int32_t, std::unique_ptr<Thread>> threads_;
std::array<std::deque<int32_t>, kPriorities> ready_;
uint64_t readyMask_[2] = {0, 0}; // bit p: ready_[p] not empty (kept by noteQueue after every change)
void noteQueue(uint32_t p);
int32_t running_ = 0;
bool switchRequested_ = false;
uint64_t picks_ = 0; // a rotation of the running thread's queue: the next transfer gives way
+6 -2
View File
@@ -18,6 +18,8 @@
#include <map>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace bozo::host
@@ -128,8 +130,10 @@ namespace bozo::host
FreeOptions opt_;
ee::Dispatcher *d_ = nullptr;
libs::Libraries libs_;
std::map<uint32_t, port::Function> portAt_;
std::map<uint32_t, const libs::Function *> nativeAt_;
// Looked up at every out-call (a few thousand a frame in a match): hashed.
std::unordered_map<uint32_t, port::Function> portAt_;
std::unordered_map<uint32_t, const libs::Function *> nativeAt_;
std::unordered_set<uint32_t> flushCacheAt_; // the kernel's FlushCache entries (kernelCallEnd)
std::map<uint32_t, std::string> names_;
std::map<uint32_t, uint64_t> perOverride_;
uint32_t insideDepth_ = 0;
+7
View File
@@ -29,6 +29,8 @@ namespace bozo::render::gl
using GLubyte = unsigned char;
using GLintptr = std::ptrdiff_t;
using GLsizeiptr = std::ptrdiff_t;
using GLuint64 = uint64_t;
using GLsync = struct __GLsync *;
// ---- Constants (OpenGL 3.3 core) ----
constexpr GLenum kFalse = 0, kTrue = 1;
@@ -47,6 +49,8 @@ namespace bozo::render::gl
constexpr GLenum kArrayBuffer = 0x8892, kPixelPackBuffer = 0x88EB;
constexpr GLenum kStreamDraw = 0x88E0, kStreamRead = 0x88E1, kDynamicDraw = 0x88E8;
constexpr GLbitfield kMapReadBit = 0x0001;
constexpr GLenum kSyncGpuCommandsComplete = 0x9117, kAlreadySignaled = 0x911A, kConditionSatisfied = 0x911C;
constexpr GLenum kDepthStencil = 0x84F9, kUnsignedInt248 = 0x84FA, kDepth24Stencil8 = 0x88F0, kDepthStencilAttachment = 0x821A;
constexpr GLenum kFramebuffer = 0x8D40, kReadFramebuffer = 0x8CA8, kDrawFramebuffer = 0x8CA9, kRenderbuffer = 0x8D41;
constexpr GLenum kColorAttachment0 = 0x8CE0, kDepthAttachment = 0x8D00, kFramebufferComplete = 0x8CD5;
constexpr GLenum kVertexShader = 0x8B31, kFragmentShader = 0x8B30;
@@ -76,6 +80,9 @@ namespace bozo::render::gl
X(void, ReadPixels, (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels)) \
X(void, GetIntegerv, (GLenum name, GLint *data)) \
X(void, Finish, (void)) \
X(GLsync, FenceSync, (GLenum condition, GLbitfield flags)) \
X(GLenum, ClientWaitSync, (GLsync sync, GLbitfield flags, GLuint64 timeout)) \
X(void, DeleteSync, (GLsync sync)) \
X(GLuint, CreateShader, (GLenum type)) \
X(void, ShaderSource, (GLuint shader, GLsizei count, const GLchar *const *strings, const GLint *lengths)) \
X(void, CompileShader, (GLuint shader)) \
+17
View File
@@ -238,6 +238,10 @@ namespace bozo::render
// The draw lists published since the last call, folded (the reference record's `draws`), and restarted: the
// host takes it at each game frame's end.
FrameDraws takeFrameDraws();
// Whether the draw lists are folded into that digest (on by default: the call-log checks and a record need it).
// A host that never takes it (free play, no record written) turns it off: hashing every vertex a frame is
// ~0.25 ms of a busy 1P frame.
void setDrawDigest(bool on) { m_digestDraws = on; }
private:
Renderer();
@@ -250,6 +254,19 @@ namespace bozo::render
Frame m_building;
Frame m_overlayBuilding;
bool m_digestDraws = true;
// Published frames come back here when their last holder lets go (their vectors' capacity kept), and the next
// frame is built in one: a busy frame's vertices (several MB) were a fresh allocation, grown by doubling and
// its pages touched for the first time, every frame. Shared with the frames' deleters (any thread).
struct FramePool
{
std::mutex mutex;
std::vector<Frame *> free;
~FramePool();
};
std::shared_ptr<FramePool> m_pool = std::make_shared<FramePool>();
// A published frame holding m_building's content (m_building gets a recycled frame's emptied vectors).
std::shared_ptr<Frame> takeBuilt(Frame &building);
bool m_enabled = false;
bool m_presentsAlone = false;
bool m_streamDraws = false;
+7 -3
View File
@@ -12,6 +12,7 @@
#include "bozo/libs/libraries.h"
#include <cfenv>
#include <xmmintrin.h>
#include <cmath>
#include <cstring>
@@ -21,11 +22,14 @@ namespace bozo::libs
{
// ---- VU0 arithmetic --------------------------------------------------------------------------------------
// The host's float arithmetic is SSE's (x86-64): its rounding control, MXCSR bits 13-14 (11: toward zero), set
// directly. std::fesetround did the same plus the x87 control word, through the C runtime's calls: ~2% of the
// game thread in a 1P match (a few thousand programs a frame).
struct TowardZero
{
int saved = std::fegetround();
TowardZero() { std::fesetround(FE_TOWARDZERO); }
~TowardZero() { std::fesetround(saved); }
unsigned saved = _mm_getcsr();
TowardZero() { _mm_setcsr(saved | 0x6000u); }
~TowardZero() { _mm_setcsr(saved); }
};
uint32_t bits(float f)
+140 -55
View File
@@ -246,12 +246,30 @@ void main()
std::unordered_map<uint64_t, GpuTexture> overlayTextures;
gl::GLuint displayPicture = 0; // the display's circuit 2 picture (bozo::render::displayPicture), its version
uint64_t displayPictureVersion = 0;
// The depth tiles read into a pixel-pack buffer at a present, taken at the next.
gl::GLuint depthPbo = 0;
size_t depthPboBytes = 0;
std::vector<uint64_t> depthPending; // the tiles in the buffer, in order (T x T floats each)
std::vector<int> depthPendingSize; // each one's read width and height
int depthPendingWidth = 0, depthPendingHeight = 0;
// The depth tiles read into a ring of pixel-pack buffers, each read fenced and taken at a later present once its
// fence has passed, never waited for. (One buffer, mapped at the present after its read, waited there for the
// GPU to finish that whole frame: in a 1P match the window thread blocked there ~70% of the time and the
// presents fell to 15-45 a second while the game kept 60.)
// A run of tiles along a tile row (tx0 to tx1), read as one rectangle: width x height depth words at offset.
struct DepthRun
{
int ty, tx0, tx1, width, height;
size_t offset;
};
struct DepthRead
{
gl::GLuint pbo = 0;
size_t bytes = 0;
gl::GLsync fence = nullptr; // set while the read is in flight
std::vector<DepthRun> runs; // what the buffer holds, run by run
size_t used = 0; // its bytes
int width = 0, height = 0;
uint64_t serial = 0; // which read it was (the newest completed one is taken)
};
static constexpr int kDepthReads = 3;
DepthRead depthReads[kDepthReads];
int depthNext = 0; // the slot the next read tries first
uint64_t depthSerial = 0;
gl::GLuint makeTexture(const uint32_t *rgba, int width, int height, gl::GLenum wrap)
{
@@ -351,9 +369,17 @@ void main()
g.DeleteRenderbuffers(1, &depth);
if (fbo != 0)
g.DeleteFramebuffers(1, &fbo);
for (gl::GLuint *b : {&vbo, &flatVbo, &depthPbo})
for (gl::GLuint *b : {&vbo, &flatVbo})
if (*b != 0)
g.DeleteBuffers(1, b);
for (DepthRead &r : depthReads)
{
if (r.fence)
g.DeleteSync(r.fence);
if (r.pbo != 0)
g.DeleteBuffers(1, &r.pbo);
r = DepthRead{};
}
for (gl::GLuint *a : {&vao, &flatVao})
if (*a != 0)
g.DeleteVertexArrays(1, a);
@@ -383,10 +409,13 @@ void main()
g.TexParameteri(gl::kTexture2D, gl::kTextureMinFilter, static_cast<gl::GLint>(gl::kNearest));
targetFiltered = false;
g.BindRenderbuffer(gl::kRenderbuffer, depth);
g.RenderbufferStorage(gl::kRenderbuffer, gl::kDepthComponent24, width, height);
// Depth with stencil: the format the hardware keeps depth in, so readDepthTiles' reads of it
// (DEPTH_STENCIL, UNSIGNED_INT_24_8) are plain copies. A 24-bit depth read as floats went through the
// driver's conversion and waited for the GPU at every present.
g.RenderbufferStorage(gl::kRenderbuffer, gl::kDepth24Stencil8, width, height);
g.BindFramebuffer(gl::kFramebuffer, fbo);
g.FramebufferTexture2D(gl::kFramebuffer, gl::kColorAttachment0, gl::kTexture2D, colour, 0);
g.FramebufferRenderbuffer(gl::kFramebuffer, gl::kDepthAttachment, gl::kRenderbuffer, depth);
g.FramebufferRenderbuffer(gl::kFramebuffer, gl::kDepthStencilAttachment, gl::kRenderbuffer, depth);
const bool complete = g.CheckFramebufferStatus(gl::kFramebuffer) == gl::kFramebufferComplete;
g.BindFramebuffer(gl::kFramebuffer, 0);
if (!complete)
@@ -1346,8 +1375,12 @@ void main()
return true;
}
// The depth tiles depthAt asked for in the last half second: read from the target (bound) into a pixel-pack buffer
// now, taken from the buffer the next present (one present late, so the read does not wait for the GPU).
// The depth tiles depthAt asked for in the last half second: read from the target (bound) into one of a ring of
// pixel-pack buffers and fenced; the newest read whose fence has passed is taken at a later present (the next one
// or the one after, as the GPU goes). Nothing here waits for the GPU: with every buffer still in flight, this
// present reads nothing and depthAt keeps the tiles it has. The tiles are read by runs along their rows (one
// ReadPixels a run, neighbours a gap of up to two tiles apart joined): a night arena's headlights want hundreds of
// tiles a present, and a ReadPixels each (up to 1,400 a present) held the window thread for most of the frame.
void Renderer::readDepthTiles(int w, int h, const Screen &screen)
{
const gl::Api &g = gl::api();
@@ -1370,64 +1403,116 @@ void main()
else
tiles.push_back((it++)->first);
}
constexpr size_t kTileBytes = static_cast<size_t>(kDepthTile) * kDepthTile * sizeof(float);
// The previous present's tiles, if they were of this size.
if (!gpu.depthPending.empty() && gpu.depthPbo != 0)
// The reads completed by now: the newest is taken, the older ones dropped.
int done = -1;
for (int i = 0; i < Gpu::kDepthReads; ++i)
{
std::unordered_map<uint64_t, std::vector<float>> depth;
if (gpu.depthPendingWidth == w && gpu.depthPendingHeight == h)
Gpu::DepthRead &r = gpu.depthReads[i];
if (!r.fence)
continue;
const gl::GLenum state = g.ClientWaitSync(r.fence, 0, 0);
if (state != gl::kAlreadySignaled && state != gl::kConditionSatisfied)
continue;
g.DeleteSync(r.fence);
r.fence = nullptr;
if (r.width != w || r.height != h || r.runs.empty() || (done >= 0 && gpu.depthReads[done].serial > r.serial))
{
g.BindBuffer(gl::kPixelPackBuffer, gpu.depthPbo);
const auto *mapped = static_cast<const float *>(
g.MapBufferRange(gl::kPixelPackBuffer, 0, static_cast<gl::GLsizeiptr>(gpu.depthPending.size() * kTileBytes), gl::kMapReadBit));
if (mapped)
{
for (size_t i = 0; i < gpu.depthPending.size(); ++i)
{
const int cw = gpu.depthPendingSize[2 * i], ch = gpu.depthPendingSize[2 * i + 1];
const float *src = mapped + i * kDepthTile * kDepthTile;
std::vector<float> &tile = depth[gpu.depthPending[i]];
tile.assign(static_cast<size_t>(kDepthTile) * kDepthTile, 1.0f); // past the edge: far
for (int r = 0; r < ch; ++r) // read bottom-up, kept top-down
std::memcpy(&tile[static_cast<size_t>(ch - 1 - r) * kDepthTile], src + static_cast<size_t>(r) * cw,
static_cast<size_t>(cw) * sizeof(float));
}
g.UnmapBuffer(gl::kPixelPackBuffer);
}
g.BindBuffer(gl::kPixelPackBuffer, 0);
r.runs.clear();
continue;
}
if (done >= 0)
gpu.depthReads[done].runs.clear();
done = i;
}
if (done >= 0)
{
Gpu::DepthRead &r = gpu.depthReads[done];
std::unordered_map<uint64_t, std::vector<float>> depth;
g.BindBuffer(gl::kPixelPackBuffer, r.pbo);
const auto *mapped = static_cast<const uint32_t *>(
g.MapBufferRange(gl::kPixelPackBuffer, 0, static_cast<gl::GLsizeiptr>(r.used), gl::kMapReadBit));
if (mapped)
{
for (const Gpu::DepthRun &run : r.runs)
{
const uint32_t *src = mapped + run.offset / sizeof(uint32_t);
for (int tx = run.tx0; tx <= run.tx1; ++tx)
{
const int x0 = (tx - run.tx0) * kDepthTile;
const int cw = std::min(kDepthTile, run.width - x0);
if (cw <= 0)
break;
std::vector<float> &tile = depth[static_cast<uint64_t>(run.ty) << 32 | static_cast<uint32_t>(tx)];
tile.assign(static_cast<size_t>(kDepthTile) * kDepthTile, 1.0f); // past the edge: far
for (int row = 0; row < run.height; ++row) // read bottom-up, kept top-down
{
// Depth in the top 24 bits (stencil below), as the window's [0, 1]: d / (2^24 - 1).
const uint32_t *in = src + static_cast<size_t>(row) * run.width + x0;
float *out = &tile[static_cast<size_t>(run.height - 1 - row) * kDepthTile];
for (int x = 0; x < cw; ++x)
out[x] = static_cast<float>(in[x] >> 8) / 16777215.0f;
}
}
}
g.UnmapBuffer(gl::kPixelPackBuffer);
}
g.BindBuffer(gl::kPixelPackBuffer, 0);
r.runs.clear();
std::lock_guard<std::mutex> lock(m_depthMutex);
m_depthTiles.swap(depth);
}
gpu.depthPending.clear();
gpu.depthPendingSize.clear();
if (tiles.empty())
return;
const size_t bytes = tiles.size() * kTileBytes;
if (gpu.depthPbo == 0)
g.GenBuffers(1, &gpu.depthPbo);
g.BindBuffer(gl::kPixelPackBuffer, gpu.depthPbo);
if (bytes > gpu.depthPboBytes)
// A free slot; none: every read still in flight, nothing read at this present.
int slot = -1;
for (int k = 0; k < Gpu::kDepthReads && slot < 0; ++k)
{
gpu.depthPboBytes = std::max(bytes, gpu.depthPboBytes * 2u);
g.BufferData(gl::kPixelPackBuffer, static_cast<gl::GLsizeiptr>(gpu.depthPboBytes), nullptr, gl::kStreamRead);
const int i = (gpu.depthNext + k) % Gpu::kDepthReads;
if (!gpu.depthReads[i].fence)
slot = i;
}
g.PixelStorei(gl::kPackAlignment, 4);
for (size_t i = 0; i < tiles.size(); ++i)
if (slot < 0)
return;
gpu.depthNext = (slot + 1) % Gpu::kDepthReads;
Gpu::DepthRead &r = gpu.depthReads[slot];
r.runs.clear();
// Runs along each tile row (keys sort by row, then column).
std::sort(tiles.begin(), tiles.end());
size_t bytes = 0;
for (size_t i = 0; i < tiles.size();)
{
const int tx = static_cast<int>(tiles[i] & 0xffffffffu), ty = static_cast<int>(tiles[i] >> 32);
const int x0 = tx * kDepthTile, top = ty * kDepthTile;
const int cw = std::min(kDepthTile, w - x0), ch = std::min(kDepthTile, h - top);
const int ty = static_cast<int>(tiles[i] >> 32), tx0 = static_cast<int>(tiles[i] & 0xffffffffu);
int tx1 = tx0;
size_t j = i + 1;
while (j < tiles.size() && static_cast<int>(tiles[j] >> 32) == ty && static_cast<int>(tiles[j] & 0xffffffffu) - tx1 <= 3)
tx1 = static_cast<int>(tiles[j++] & 0xffffffffu);
i = j;
const int x0 = tx0 * kDepthTile, top = ty * kDepthTile;
const int cw = std::min((tx1 + 1) * kDepthTile, w) - x0, ch = std::min(kDepthTile, h - top);
if (cw <= 0 || ch <= 0)
continue;
g.ReadPixels(x0, h - (top + ch), cw, ch, gl::kDepthComponent, gl::kFloat,
reinterpret_cast<void *>(static_cast<uintptr_t>(gpu.depthPending.size() * kTileBytes)));
gpu.depthPending.push_back(tiles[i]);
gpu.depthPendingSize.push_back(cw);
gpu.depthPendingSize.push_back(ch);
r.runs.push_back(Gpu::DepthRun{ty, tx0, tx1, cw, ch, bytes});
bytes += static_cast<size_t>(cw) * ch * sizeof(uint32_t);
}
if (r.runs.empty())
return;
if (r.pbo == 0)
g.GenBuffers(1, &r.pbo);
g.BindBuffer(gl::kPixelPackBuffer, r.pbo);
if (bytes > r.bytes)
{
r.bytes = std::max(bytes, r.bytes * 2u);
g.BufferData(gl::kPixelPackBuffer, static_cast<gl::GLsizeiptr>(r.bytes), nullptr, gl::kStreamRead);
}
g.PixelStorei(gl::kPackAlignment, 4);
for (const Gpu::DepthRun &run : r.runs)
g.ReadPixels(run.tx0 * kDepthTile, h - (run.ty * kDepthTile + run.height), run.width, run.height, gl::kDepthStencil,
gl::kUnsignedInt248, reinterpret_cast<void *>(static_cast<uintptr_t>(run.offset)));
g.BindBuffer(gl::kPixelPackBuffer, 0);
gpu.depthPendingWidth = w;
gpu.depthPendingHeight = h;
r.used = bytes;
r.width = w;
r.height = h;
r.serial = ++gpu.depthSerial;
r.fence = g.FenceSync(gl::kSyncGpuCommandsComplete, 0);
}
}
+44 -1
View File
@@ -72,8 +72,48 @@ namespace bozo::render
return renderer;
}
Renderer::FramePool::~FramePool()
{
for (Frame *f : free)
delete f;
}
std::shared_ptr<Renderer::Frame> Renderer::takeBuilt(Frame &building)
{
Frame *out = nullptr;
{
std::lock_guard<std::mutex> lock(m_pool->mutex);
if (!m_pool->free.empty())
{
out = m_pool->free.back();
m_pool->free.pop_back();
}
}
if (!out)
out = new Frame;
std::swap(*out, building); // building now holds the recycled frame's old content (emptied by startBuilding)
std::shared_ptr<FramePool> pool = m_pool;
return std::shared_ptr<Frame>(out, [pool](Frame *f)
{
// Emptied here, by whichever thread let go last (as the frame's destruction was); the capacity stays.
f->vertices.clear();
f->batches.clear();
f->triangleIds.clear();
f->keys.clear();
f->bases.clear();
f->tracked.clear();
std::lock_guard<std::mutex> lock(pool->mutex);
if (pool->free.size() < 8u)
pool->free.push_back(f);
else
delete f;
});
}
void Renderer::noteDrawList(const Frame &frame, uint64_t kind)
{
if (!m_digestDraws)
return;
static_assert(sizeof(Vertex) == 32u, "Vertex: eight 4-byte fields, no padding");
uint64_t h = hash::xxh64(&kind, sizeof(kind), 0);
for (const Batch &batch : frame.batches)
@@ -114,12 +154,15 @@ namespace bozo::render
{
std::vector<Vertex> vertices = std::move(m_building.vertices);
std::vector<Batch> batches = std::move(m_building.batches);
std::vector<uint64_t> triangleIds = std::move(m_building.triangleIds);
vertices.clear();
batches.clear();
triangleIds.clear();
m_building = Frame{};
m_building.screen = screen;
m_building.vertices = std::move(vertices);
m_building.batches = std::move(batches);
m_building.triangleIds = std::move(triangleIds);
}
void Renderer::draw(const Material &material, const float matrix[16], const Vertex *vertices, uint32_t count)
@@ -246,7 +289,7 @@ namespace bozo::render
void Renderer::endFrame()
{
noteDrawList(m_building, 1u);
auto frame = std::make_shared<Frame>(std::move(m_building));
std::shared_ptr<Frame> frame = takeBuilt(m_building);
startBuilding(Screen{});
m_key = 0;
frame->time = secondsNow();