182 auto& registry = collect_ctx.
registry;
187 if (!tilemap_system_)
return;
190 const auto& layers = tilemap_system_->allLayers();
191 if (layers.empty())
return;
196 for (
const auto& [entity, layer] : layers) {
197 auto cachedLayer = layer_caches_.find(entity);
198 if (cachedLayer != layer_caches_.end() && cachedLayer->second.generation != layer.generation) {
199 releaseLayer(cachedLayer->second);
200 layer_caches_.erase(cachedLayer);
201 cachedLayer = layer_caches_.end();
203 if (registry.valid(entity) && !registry.isEntityActive(entity))
continue;
223 glm::vec2 originOffset{0.0f, 0.0f};
236 visible = layer.visible;
237 sortLayer = layer.sort_layer;
240 opacity = layer.opacity;
241 parallax = layer.parallax_factor;
243 singleColumns = layer.tileset_columns;
246 if (registry.valid(entity)) opacity *= groupOpacity.
of(entity);
247 if (!visible)
continue;
251 const std::vector<tilemap::TilesetSlot>* slotsPtr;
252 if (!layer.tilesets.empty()) {
253 slotsPtr = &layer.tilesets;
255 if (!singleTileset.
isValid() || singleColumns == 0)
continue;
256 single_slot_scratch_.clear();
258 slotsPtr = &single_slot_scratch_;
260 const std::vector<tilemap::TilesetSlot>& slots = *slotsPtr;
264 resolved_scratch_.assign(slots.size(), ResolvedSlot{});
265 std::vector<ResolvedSlot>& resolved = resolved_scratch_;
266 bool anySlotValid =
false;
267 for (
usize i = 0; i < slots.size(); ++i) {
270 f32 tw =
static_cast<f32>(tex->getWidth());
271 f32 th =
static_cast<f32>(tex->getHeight());
272 if (tw <= 0.0f || th <= 0.0f)
continue;
273 resolved[i].valid =
true;
274 resolved[i].glTexId = tex->getId();
275 resolved[i].uvW = layer.tile_width / tw;
276 resolved[i].uvH = layer.tile_height / th;
277 f32 margin =
static_cast<f32>(slots[i].margin);
278 f32 spacing =
static_cast<f32>(slots[i].spacing);
279 resolved[i].uvOffsetX = margin / tw;
280 resolved[i].uvOffsetY = margin / th;
281 resolved[i].uvStepX = (layer.tile_width + spacing) / tw;
282 resolved[i].uvStepY = (layer.tile_height + spacing) / th;
286 const bool extruded = slots[i].extrude > 0;
287 resolved[i].insetU = extruded ? 0.0f : 0.5f / tw;
288 resolved[i].insetV = extruded ? 0.0f : 0.5f / th;
293 if (!anySlotValid)
continue;
298 u32 layerShader = batch_shader_id_;
299 if (lit &&
ctx.frame) {
303 f32 originX = 0, originY = 0, angle = 0;
305 ? layer.origin_entity : entity;
306 if (
auto* transform = registry.tryGet<
ecs::Transform>(transformEntity)) {
307 transform->ensureDecomposed();
308 originX =
rebased(transform->worldPosition).x;
309 originY =
rebased(transform->worldPosition).y;
310 const auto& q = transform->worldRotation;
311 angle = std::atan2(2.0f * (q.w * q.z + q.x * q.y),
312 1.0f - 2.0f * (q.y * q.y + q.z * q.z));
314 const f32 cosAngle = std::cos(angle), sinAngle = std::sin(angle);
316 glm::vec4 finalColor(tint.r, tint.g, tint.b, tint.a * opacity);
324 f32 adjOriginX = originX + parallaxOffsetX + originOffset.x;
325 f32 adjOriginY = originY + parallaxOffsetY + originOffset.y;
338 i32 cornerTx[4], cornerTy[4];
339 const auto cornerToTile = [&](
f32 x,
f32 y,
i32& tx,
i32& ty) {
341 tilemap_system_->worldToTile(entity, x, y, adjOriginX, adjOriginY, tx, ty);
343 const f32 dx = x - originX - parallaxOffsetX, dy = y - originY - parallaxOffsetY;
344 tilemap_system_->worldToTile(entity, dx * cosAngle + dy * sinAngle,
345 -dx * sinAngle + dy * cosAngle, originOffset.x, originOffset.y, tx, ty);
348 cornerToTile(cam.
left, cam.
top, cornerTx[0], cornerTy[0]);
349 cornerToTile(cam.
right, cam.
top, cornerTx[1], cornerTy[1]);
350 cornerToTile(cam.
left, cam.
bottom, cornerTx[2], cornerTy[2]);
351 cornerToTile(cam.
right, cam.
bottom, cornerTx[3], cornerTy[3]);
352 i32 minTx = cornerTx[0], maxTx = cornerTx[0];
353 i32 minTy = cornerTy[0], maxTy = cornerTy[0];
354 for (
int i = 1; i < 4; ++i) {
355 minTx = std::min(minTx, cornerTx[i]); maxTx = std::max(maxTx, cornerTx[i]);
356 minTy = std::min(minTy, cornerTy[i]); maxTy = std::max(maxTy, cornerTy[i]);
358 minTx -= 1; minTy -= 1; maxTx += 1; maxTy += 1;
360 i32 minCX =
static_cast<i32>(std::floor(
static_cast<f32>(minTx) /
static_cast<f32>(chunkSize)));
361 i32 minCY =
static_cast<i32>(std::floor(
static_cast<f32>(minTy) /
static_cast<f32>(chunkSize)));
362 i32 maxCX =
static_cast<i32>(std::floor(
static_cast<f32>(maxTx) /
static_cast<f32>(chunkSize))) + 1;
363 i32 maxCY =
static_cast<i32>(std::floor(
static_cast<f32>(maxTy) /
static_cast<f32>(chunkSize))) + 1;
365 if (!layer.infinite) {
368 minCX = std::max(minCX, 0);
369 minCY = std::max(minCY, 0);
370 maxCX = std::min(maxCX, chunksX);
371 maxCY = std::min(maxCY, chunksY);
374 if (minCX >= maxCX || minCY >= maxCY)
continue;
376 auto& layerCache = cachedLayer != layer_caches_.end() ? cachedLayer->second : layer_caches_[entity];
377 layerCache.generation = layer.generation;
378 const LayoutInputs layout{layer.tile_width, layer.tile_height, layer.grid_type,
379 layer.hex_side_length, layer.hex_stagger_axis_x, layer.hex_stagger_index_even};
380 if (layerCache.layout != layout || layerCache.tilesets != slots || layerCache.resolved != resolved) {
381 releaseLayer(layerCache);
382 layerCache.chunks.clear();
383 layerCache.layout = layout;
384 layerCache.tilesets = slots;
385 layerCache.resolved = resolved;
387 auto& chunkCaches = layerCache.chunks;
389 if (layerCache.chunksErasedSeen != layer.chunks_erased) {
390 for (
auto it = chunkCaches.begin(); it != chunkCaches.end();) {
391 it = layer.chunks.find(it->first) == layer.chunks.end() ? chunkCaches.erase(it) : std::next(it);
393 layerCache.chunksErasedSeen = layer.chunks_erased;
399 const Placement place{adjOriginX, adjOriginY, originX, originY, originOffset.x, originOffset.y, angle, depth, packedColor};
400 constexpr u64 SETTLE_COLLECTS = 30;
401 if (layerCache.lastPlacementKnown && !(layerCache.lastPlacement == place)) {
402 if (layerCache.movingUntil <= collect_serial_) releaseLayer(layerCache);
403 layerCache.movingUntil = collect_serial_ + SETTLE_COLLECTS;
405 layerCache.lastPlacement = place;
406 layerCache.lastPlacementKnown =
true;
407 if (parallax.x == 1.0f && parallax.y == 1.0f && layerCache.movingUntil <= collect_serial_ && buffers.device().isDeviceUsable()) {
411 const i32 firstStrip =
static_cast<i32>(std::floor(
static_cast<f32>(minCX) /
static_cast<f32>(STRIP_CHUNKS)));
412 const i32 lastStrip =
static_cast<i32>(std::floor(
static_cast<f32>(maxCX - 1) /
static_cast<f32>(STRIP_CHUNKS)));
415 visible_strips_scratch_.clear();
416 for (
i32 cy = minCY; cy < maxCY; ++cy) {
419 const auto measure = [&](
i32 cxBegin,
i32 width,
u64& stamp,
u32& chunkCount) {
422 for (
i32 cx = cxBegin; cx < cxBegin + width; ++cx) {
424 const auto chunkIt = layer.chunks.find(coord);
425 if (chunkIt == layer.chunks.end())
continue;
426 stamp = std::max(stamp, ensureChunk(layer, chunkIt->second, coord, slots, resolved, entity, chunkCaches).mesh_serial);
430 const auto refresh = [&](Strip& strip,
i32 cxBegin,
i32 width,
u64 stamp,
u32 chunkCount) {
431 const bool current = strip.built && strip.stamp == stamp && strip.chunkCount == chunkCount
432 && strip.placement == place && strip.deviceGeneration == generation && strip.slots.size() == slots.size();
434 releaseStrip(device, strip);
435 strip.slots.assign(slots.size(), StripSlot{});
436 for (
usize si = 0; si < slots.size(); ++si) {
437 if (!resolved[si].valid)
continue;
438 strip_vertices_scratch_.clear();
439 strip_indices_scratch_.clear();
441 for (
i32 cx = cxBegin; cx < cxBegin + width; ++cx) {
443 if (chunkIt == chunkCaches.end() || si >= chunkIt->second.slots.size())
continue;
445 const SlotMesh& mesh = chunkIt->second.slots[si];
446 if (mesh.indices.empty())
continue;
447 const u32 baseVertex =
static_cast<u32>(strip_vertices_scratch_.size());
450 strip_vertices_scratch_.push_back({
453 : glm::vec3{originX + parallaxOffsetX + lx * cosAngle - ly * sinAngle,
454 originY + parallaxOffsetY + lx * sinAngle + ly * cosAngle, depth},
457 for (
u32 idx : mesh.indices) strip_indices_scratch_.push_back(baseVertex + idx);
459 if (strip_indices_scratch_.empty())
continue;
460 StripSlot& out = strip.slots[si];
461 out.vertexCount =
static_cast<u32>(strip_vertices_scratch_.size());
462 out.indexCount =
static_cast<u32>(strip_indices_scratch_.size());
463 out.vboBytes = out.vertexCount *
static_cast<u32>(
sizeof(
BatchVertex));
464 out.iboBytes = out.indexCount *
static_cast<u32>(
sizeof(
u32));
466 strip_vertices_scratch_.data());
468 strip_indices_scratch_.data());
475 strip_bytes_ += out.vboBytes + out.iboBytes;
477 strip.placement = place;
479 strip.chunkCount = chunkCount;
480 strip.deviceGeneration = generation;
483 visible_strips_scratch_.push_back(&strip);
485 for (
i32 sx = firstStrip; sx <= lastStrip; ++sx) {
486 Strip& strip = layerCache.strips[StripKey{sx, cy}];
487 strip.lastUsed = collect_serial_;
488 const i32 cxBegin = sx * STRIP_CHUNKS;
491 measure(cxBegin, STRIP_CHUNKS, stamp, chunkCount);
492 const bool held = strip.built || !strip.pieces.empty();
493 if (chunkCount == 0 && !held)
continue;
494 if (held && (strip.stamp != stamp || strip.chunkCount != chunkCount)) strip.piecesUntil = collect_serial_ + STRIP_PIECES_COLLECTS;
495 if (strip.piecesUntil > collect_serial_) {
496 if (strip.built) releaseStrip(device, strip);
497 if (strip.pieces.empty()) strip.pieces.resize(STRIP_CHUNKS / STRIP_PIECE_CHUNKS);
499 strip.chunkCount = chunkCount;
500 for (
usize i = 0; i < strip.pieces.size(); ++i) {
501 Strip& piece = strip.pieces[i];
502 const i32 pieceBegin = cxBegin +
static_cast<i32>(i) * STRIP_PIECE_CHUNKS;
505 measure(pieceBegin, STRIP_PIECE_CHUNKS, pieceStamp, pieceChunks);
506 if (pieceChunks == 0 && !piece.built)
continue;
507 refresh(piece, pieceBegin, STRIP_PIECE_CHUNKS, pieceStamp, pieceChunks);
511 if (!strip.pieces.empty()) releaseStrip(device, strip);
512 refresh(strip, cxBegin, STRIP_CHUNKS, stamp, chunkCount);
517 for (
usize si = 0; si < slots.size(); ++si) {
518 if (!resolved[si].valid)
continue;
519 for (
const Strip* strip : visible_strips_scratch_) {
520 if (si >= strip->slots.size() || strip->slots[si].indexCount == 0)
continue;
521 const StripSlot& slot = strip->slots[si];
523 .stage =
ctx.current_stage,
525 .shaderId = layerShader,
527 .textureId = resolved[si].glTexId,
536 pushBatchDraw(draw_list, clips, 0, slot.vertexCount, 0, slot.indexCount, key);
543 if (slot_vertices_scratch_.size() < slots.size()) {
544 slot_vertices_scratch_.resize(slots.size());
545 slot_indices_scratch_.resize(slots.size());
547 for (
usize si = 0; si < slots.size(); ++si) {
548 slot_vertices_scratch_[si].clear();
549 slot_indices_scratch_[si].clear();
551 std::vector<std::vector<BatchVertex>>& slotVertices = slot_vertices_scratch_;
552 std::vector<std::vector<u32>>& slotIndices = slot_indices_scratch_;
554 for (
i32 cy = minCY; cy < maxCY; ++cy) {
555 for (
i32 cx = minCX; cx < maxCX; ++cx) {
557 auto chunkIt = layer.chunks.find(coord);
558 if (chunkIt == layer.chunks.end())
continue;
560 const auto& chunkData = chunkIt->second;
561 auto& cache = ensureChunk(layer, chunkData, coord, slots, resolved, entity, chunkCaches);
563 for (
usize si = 0; si < slots.size() && si < cache.slots.size(); ++si) {
564 const SlotMesh& mesh = cache.slots[si];
565 if (mesh.indices.empty())
continue;
566 u32 baseVertex =
static_cast<u32>(slotVertices[si].size());
569 slotVertices[si].push_back({
572 : glm::vec3{originX + parallaxOffsetX + lx * cosAngle - ly * sinAngle,
573 originY + parallaxOffsetY + lx * sinAngle + ly * cosAngle, depth},
576 for (
u32 idx : mesh.indices) {
577 slotIndices[si].push_back(baseVertex + idx);
585 for (
usize si = 0; si < slots.size(); ++si) {
586 if (!resolved[si].valid || slotIndices[si].empty())
continue;
588 slotVertices[si].data(),
static_cast<u32>(slotVertices[si].size()),
589 slotIndices[si].data(),
static_cast<u32>(slotIndices[si].size()),
591 .stage =
ctx.current_stage,
593 .shaderId = layerShader,
595 .textureId = resolved[si].glTexId,
606 for (
auto it = layer_caches_.begin(); it != layer_caches_.end(); ) {
607 if (layers.find(it->first) == layers.end()) {
608 releaseLayer(it->second);
609 it = layer_caches_.erase(it);
614 if (device_) evictStrips(*device_);