Skip to content

Refactor GameBoard Rendering Architecture#171

Merged
candour merged 3 commits into
mainfrom
refactor-gameboard-rendering-4478512731080798057
May 26, 2026
Merged

Refactor GameBoard Rendering Architecture#171
candour merged 3 commits into
mainfrom
refactor-gameboard-rendering-4478512731080798057

Conversation

@candour
Copy link
Copy Markdown
Owner

@candour candour commented May 25, 2026

This PR refactors the core rendering loop in GameBoard.kt to significantly improve performance and maintainability.

Key changes include:

  1. Layered Rendering: Drawing is now split into four distinct passes:
    • Background: Static floor and edge tiles.
    • Decals: Ground-level markers, drains, puddles, and persistent effects.
    • World: Entities requiring depth sorting (pillars, stalls, enemies, goal table).
    • Foreground: UI elements, projectiles, and overhead effects.
  2. Zero-Allocation Rendering: Removed the creation of DrawableEntity objects and captured lambdas in the onDraw loop. Instead, a pre-allocated pool of WorldItem objects is used to collect and sort world entities.
  3. Optimized Sorting: Depth sorting is now localized to the World layer and uses a stable, pre-allocated Comparator, reducing the complexity and overhead of sorting all drawables together.
  4. Consistency: Aligned the rendering logic with the architectural guidelines in AGENTS.md.

These changes reduce garbage collection pressure on the UI thread and ensure correct isometric depth rendering across all entity types.


PR created automatically by Jules for task 4478512731080798057 started by @candour

Summary by CodeRabbit

  • Refactor
    • Redesigned rendering into explicit background/decals/world/foreground passes for smoother, more consistent visuals
    • Reduced runtime overhead for faster frame rates and lower stutter
    • Projectiles now animate with multi-segment interpolation and optional arc for more natural trajectories
    • Certain effects (puddles, decals) render earlier; gas clouds and money spray render in front for correct layering
    • Selection/range indicators and upgrade badges reliably appear in the foreground

Review Change Stack

- Implemented explicit rendering passes for Background, Decals, World, and Foreground layers as per AGENTS.md.
- Replaced the high-allocation `DrawableEntity` logic with a zero-allocation pooled `WorldItem` system.
- Optimized depth sorting in the World layer using a singleton `WorldItemComparator` on pooled entities.
- Consolidated ground-level decals and overhead effects into their respective layers.
- Updated `fixes.md` with REF-014 to document the architectural improvement.

Co-authored-by: candour <4670475+candour@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 25, 2026

📝 Walkthrough

Walkthrough

GameBoard.kt's rendering pipeline was refactored from deferred DrawableEntity + sorted drawables to explicit layered direct rendering: background, decals, pooled/sorted world entities, and foreground. Projectile interpolation, selection/range indicators, and upgrade badges moved into direct foreground drawing. A changelog entry (REF-014) was added.

Changes

GameBoard Rendering Architecture Refactor

Layer / File(s) Summary
Rendering infrastructure & pooling
app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
Removed DrawableEntity abstraction, converted WorldItem into a mutable pooled holder with expanded fields and set(...), and added WorldItemComparator ordering by r, then zOrder, then q.
Layer-1 & Layer-2: Background and decals
app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
Background and decals now draw immediately during their layer pass rather than being queued as deferred drawables.
Layer-3: World entity pooling and depth-sorted rendering
app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
Introduced pooled WorldItem list reused each frame, populated from hex tiles and enemies, sorted with WorldItemComparator, and drawn as world entities (pillars, goal table, stalls, enemies) with non-foreground VFX rendered in this pass.
Layer-4: Foreground effects, projectiles, selection, and badges
app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
Gas clouds and money spray rendered in foreground; projectiles use 5-segment interpolation with optional arc displacement; selection/range visuals and stall upgrade badges drawn in the foreground pass.
Changelog documentation
fixes.md
Added REF-014 entry describing the layered zero-allocation rendering refactor and pooled stable depth-sorting.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • candour/towerpower#140: Related refactor of GameBoard rendering to layered pass-based flow with updated depth-sorting and world item handling.
  • candour/towerpower#141: Overlapping changes to projectile and VFX placement in GameBoard render flow.
  • candour/towerpower#142: Earlier queued DrawableEntity/drawables z-sorting approach that this PR replaces with explicit passes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Refactor GameBoard Rendering Architecture' directly and clearly summarizes the main change: a comprehensive refactoring of the GameBoard rendering system from deferred drawables to a layered, pooled architecture.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor-gameboard-rendering-4478512731080798057

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown

Build Successful! 🚀

Download APK

Note: This link will be removed when the PR is closed.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt (2)

141-146: ⚡ Quick win

Sorting is missing the zOrder tiebreaker between r and q.

The comparator sorts by r then directly by q, but coding guidelines specify sorting by r, then zOrder, then q for correct isometric depth. Without zOrder, entities of different types at the same row (e.g., a stall and enemy at similar r) may render in incorrect depth order.

Consider adding a zOrder field to WorldItem and updating the comparator:

Suggested approach
 private class WorldItem {
     var q: Float = 0f
     var r: Float = 0f
+    var zOrder: Int = 0
     var type: WorldItemType = WorldItemType.PILLAR
     // ...
 }

 private object WorldItemComparator : Comparator<WorldItem> {
     override fun compare(a: WorldItem, b: WorldItem): Int {
         val rComp = a.r.compareTo(b.r)
-        return if (rComp != 0) rComp else a.q.compareTo(b.q)
+        if (rComp != 0) return rComp
+        val zComp = a.zOrder.compareTo(b.zOrder)
+        return if (zComp != 0) zComp else a.q.compareTo(b.q)
     }
 }

Then assign appropriate zOrder values when populating items (e.g., PILLAR=0, STALL=1, ENEMY=2).

As per coding guidelines: "Sort World layer entities (zOrder group 2) strictly by axial r (row) coordinate, then by zOrder, then by q (column) for correct isometric depth".


333-344: 💤 Low value

Silent pool exhaustion may cause entities to disappear without warning.

If poolIdx reaches 512, additional world entities are silently dropped and won't render. While 512 is likely sufficient for typical gameplay, edge cases (large maps, many enemies) could trigger this.

Consider adding a debug assertion or log to surface this during development:

Suggested addition
 enemies.forEach { enemy ->
     if (poolIdx < worldItemPool.size) {
         val item = worldItemPool[poolIdx++]
         item.set(enemy.position.q, enemy.position.r, WorldItemType.ENEMY, null, null, enemy, ctx.toScreenPrecise(enemy.position.q, enemy.position.r))
         activeWorldItems.add(item)
+    } else {
+        // Log.w("GameBoard", "WorldItem pool exhausted, dropping entity")
     }
 }

Also applies to: 348-352


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ccc8319-dbad-4284-9408-b8bf10df0501

📥 Commits

Reviewing files that changed from the base of the PR and between 1a4497d and c021ccd.

📒 Files selected for processing (2)
  • app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
  • fixes.md

Comment thread fixes.md Outdated
@candour
Copy link
Copy Markdown
Owner Author

candour commented May 25, 2026

Sorting is missing the zOrder tiebreaker between r and q.

The comparator sorts by r then directly by q, but coding guidelines specify sorting by r, then zOrder, then q for correct isometric depth. Without zOrder, entities of different types at the same row (e.g., a stall and enemy at similar r) may render in incorrect depth order.

@candour candour enabled auto-merge (squash) May 25, 2026 22:08
@candour
Copy link
Copy Markdown
Owner Author

candour commented May 25, 2026

If poolIdx reaches 512, additional world entities are silently dropped and won't render. While 512 is likely sufficient for typical gameplay, edge cases (large maps, many enemies) could trigger this.

Consider adding a debug assertion or log to surface this during development:

@google-labs-jules
Copy link
Copy Markdown
Contributor

Sorting is missing the zOrder tiebreaker between r and q.

The comparator sorts by r then directly by q, but coding guidelines specify sorting by r, then zOrder, then q for correct isometric depth. Without zOrder, entities of different types at the same row (e.g., a stall and enemy at similar r) may render in incorrect depth order.

Good catch. I've updated the WorldItem class to include zOrder and modified WorldItemComparator to use it as a tiebreaker between r and q, ensuring correct isometric depth as per the guidelines.

- Updated `WorldItem` to track `zOrder`.
- Modified `WorldItemComparator` to sort by `r`, then `zOrder`, then `q`.
- Updated `fixes.md` to reflect the refined sorting logic.

Co-authored-by: candour <4670475+candour@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown

Build Successful! 🚀

Download APK

Note: This link will be removed when the PR is closed.

@candour
Copy link
Copy Markdown
Owner Author

candour commented May 26, 2026

Silent pool exhaustion may cause entities to disappear without warning.

If poolIdx reaches 512, additional world entities are silently dropped and won't render. While 512 is likely sufficient for typical gameplay, edge cases (large maps, many enemies) could trigger this.

@google-labs-jules
Copy link
Copy Markdown
Contributor

Silent pool exhaustion may cause entities to disappear without warning.

If poolIdx reaches 512, additional world entities are silently dropped and won't render. While 512 is likely sufficient for typical gameplay, edge cases (large maps, many enemies) could trigger this.

Good point. I've added a Log.w warning that triggers once per frame if the pool is exhausted. This should make it obvious during development if we need to increase the pool size, while maintaining the zero-allocation performance goals.

- Added `android.util.Log.w` warning when the pre-allocated entity pool is exhausted.
- Ensured `poolIdx` continues to increment to correctly trigger the warning only once per frame.

Co-authored-by: candour <4670475+candour@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown

Build Successful! 🚀

Download APK

Note: This link will be removed when the PR is closed.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b45f31ad-2af4-4044-add9-5aae91ef2c9d

📥 Commits

Reviewing files that changed from the base of the PR and between c021ccd and e6dd008.

📒 Files selected for processing (2)
  • app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
  • fixes.md
✅ Files skipped from review due to trivial changes (1)
  • fixes.md

Comment thread app/src/main/java/com/messark/hawker/ui/components/GameBoard.kt
@candour candour merged commit 2eb35a9 into main May 26, 2026
3 checks passed
@candour candour deleted the refactor-gameboard-rendering-4478512731080798057 branch May 26, 2026 05:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant