init commit

This commit is contained in:
Luxferre committed 2026-11-30 22:31:51 +02:00
commit 15ab48343a
187 files changed
+12644

No files matched your search

+270
View File
@@ -0,0 +1,270 @@
#include "assets/flic.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cstring>
namespace top_octane::assets {
namespace {
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
inline int16_t read_le16s(const uint8_t* p) {
return static_cast<int16_t>(read_le16(p));
}
inline uint32_t read_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
} // namespace
bool FlicPlayer::open(const Vfs& vfs, const std::string& path) {
if (!vfs.read_file(path, file_data_)) {
LOG_ERROR("Failed to read FLIC file: %s", path.c_str());
return false;
}
if (file_data_.size() < 16) return false;
uint32_t hdr_len = read_le32(file_data_.data() + 0);
uint16_t magic = read_le16(file_data_.data() + 4);
if (magic == 0xAF12 || magic == 0xAF11) {
num_frames_ = read_le16(file_data_.data() + 6);
width_ = read_le16(file_data_.data() + 8);
height_ = read_le16(file_data_.data() + 10);
} else {
LOG_ERROR("Unsupported FLIC magic %04x in %s", magic, path.c_str());
return false;
}
if (width_ <= 0 || height_ <= 0 || hdr_len >= file_data_.size()) {
return false;
}
// Standard FLC uses 128B header; Bullfrog INTRO.DAT uses a 12-byte compact header followed immediately by 0xF1FA!
size_t first_off = hdr_len;
if (first_off + 6 <= file_data_.size() && read_le16(file_data_.data() + first_off + 4) != 0xF1FA) {
// Fallback scan for first 0xF1FA chunk header
first_off = 128;
for (size_t i = hdr_len; i + 6 <= std::min<size_t>(file_data_.size(), 256); ++i) {
if (read_le16(file_data_.data() + i + 4) == 0xF1FA) {
first_off = i - 0; // wait: magic is at chunk+4, so chunk starts at i!
break;
}
}
}
// Verify chunk start at first_off has 0xF1FA at +4
if (first_off + 16 > file_data_.size() || read_le16(file_data_.data() + first_off + 4) != 0xF1FA) {
LOG_ERROR("Could not locate first 0xF1FA FLC frame chunk in %s", path.c_str());
return false;
}
indexed_.assign(static_cast<size_t>(width_) * height_, 0);
rgba_.assign(static_cast<size_t>(width_) * height_ * 4u, 0);
next_frame_offset_ = first_off;
frame_index_ = 0;
return true;
}
void FlicPlayer::reset() {
if (file_data_.size() < 16) return;
uint32_t hdr_len = read_le32(file_data_.data() + 0);
next_frame_offset_ = hdr_len;
frame_index_ = 0;
std::fill(indexed_.begin(), indexed_.end(), 0);
std::fill(rgba_.begin(), rgba_.end(), 0);
}
bool FlicPlayer::step_frame() {
if (frame_index_ >= num_frames_ || next_frame_offset_ + 16 > file_data_.size()) {
return false;
}
if (!decode_chunk_frame(next_frame_offset_)) {
return false;
}
++frame_index_;
const size_t pixels = static_cast<size_t>(width_) * height_;
for (size_t i = 0; i < pixels; ++i) {
const Rgba8& c = palette_[indexed_[i]];
rgba_[i * 4 + 0] = c.r;
rgba_[i * 4 + 1] = c.g;
rgba_[i * 4 + 2] = c.b;
rgba_[i * 4 + 3] = 255;
}
return true;
}
bool FlicPlayer::decode_chunk_frame(size_t offset) {
const uint8_t* base = file_data_.data();
const size_t total = file_data_.size();
// Advance past optional prefix/non-frame chunks if any
while (offset + 16 <= total) {
uint32_t fsize = read_le32(base + offset);
uint16_t ftype = read_le16(base + offset + 4);
if (fsize < 6 || offset + fsize > total) {
return false;
}
if (ftype == 0xF1FA) {
uint16_t chunks = read_le16(base + offset + 6);
size_t pos = offset + 16;
size_t frame_end = offset + fsize;
for (uint16_t c = 0; c < chunks && pos + 6 <= frame_end; ++c) {
uint32_t csize = read_le32(base + pos);
uint16_t ctype = read_le16(base + pos + 4);
const uint8_t* cd = base + pos + 6;
size_t cdata_len = (csize >= 6 && pos + csize <= frame_end) ? (csize - 6) : 0;
switch (ctype) {
case 4: // FLI_COLOUR256 (0..255 8-bit RGB)
case 11: { // FLI_COLOUR (0..63 6-bit RGB)
if (cdata_len >= 2) {
uint16_t packets = read_le16(cd);
size_t cp = 2;
int idx = 0;
for (uint16_t pk = 0; pk < packets && cp + 2 <= cdata_len; ++pk) {
idx += cd[cp++];
int cnt = cd[cp++];
if (cnt == 0) cnt = 256;
for (int k = 0; k < cnt && cp + 3 <= cdata_len && idx < 256; ++k, ++idx) {
uint8_t r = cd[cp++], g = cd[cp++], b = cd[cp++];
if (ctype == 11) {
r = static_cast<uint8_t>((r << 2) | (r >> 4));
g = static_cast<uint8_t>((g << 2) | (g >> 4));
b = static_cast<uint8_t>((b << 2) | (b >> 4));
}
palette_[idx] = {r, g, b, 255};
}
}
}
break;
}
case 13: { // FLI_BLACK
std::fill(indexed_.begin(), indexed_.end(), 0);
break;
}
case 16: { // FLI_COPY
size_t n = std::min(indexed_.size(), cdata_len);
std::memcpy(indexed_.data(), cd, n);
break;
}
case 15: { // FLI_BRUN
size_t cp = 0;
for (int y = 0; y < height_ && cp < cdata_len; ++y) {
cp++; // packet count byte (unused in FLC; line width drives loop)
int x = 0;
while (x < width_ && cp < cdata_len) {
int8_t cnt = static_cast<int8_t>(cd[cp++]);
if (cnt > 0) {
if (cp >= cdata_len) break;
uint8_t val = cd[cp++];
for (int k = 0; k < cnt && x < width_; ++k, ++x) {
indexed_[static_cast<size_t>(y) * width_ + x] = val;
}
} else if (cnt < 0) {
int run = -cnt;
for (int k = 0; k < run && x < width_ && cp < cdata_len; ++k, ++x) {
indexed_[static_cast<size_t>(y) * width_ + x] = cd[cp++];
}
}
}
}
break;
}
case 12: { // FLI_LC (line delta 8-bit)
if (cdata_len >= 4) {
int y = read_le16(cd + 0);
int lines = read_le16(cd + 2);
size_t cp = 4;
for (int l = 0; l < lines && y < height_ && cp < cdata_len; ++l, ++y) {
uint8_t packets = cd[cp++];
int x = 0;
for (uint8_t pk = 0; pk < packets && cp < cdata_len; ++pk) {
x += cd[cp++];
if (cp >= cdata_len) break;
int8_t cnt = static_cast<int8_t>(cd[cp++]);
if (cnt > 0) {
for (int k = 0; k < cnt && x < width_ && cp < cdata_len; ++k, ++x) {
indexed_[static_cast<size_t>(y) * width_ + x] = cd[cp++];
}
} else if (cnt < 0) {
if (cp >= cdata_len) break;
uint8_t val = cd[cp++];
int run = -cnt;
for (int k = 0; k < run && x < width_; ++k, ++x) {
indexed_[static_cast<size_t>(y) * width_ + x] = val;
}
}
}
}
}
break;
}
case 7: { // FLI_SS2 (word delta)
if (cdata_len >= 2) {
int lines = read_le16(cd);
size_t cp = 2;
int y = 0;
for (int l = 0; l < lines && y < height_ && cp + 2 <= cdata_len;) {
int16_t word = read_le16s(cd + cp);
cp += 2;
if ((word & 0xC000) == 0xC000) {
y += -word;
} else if ((word & 0xC000) == 0x4000) {
// odd last byte + packets
uint8_t last_b = static_cast<uint8_t>(word & 0xFF);
if (width_ > 0) {
indexed_[static_cast<size_t>(y) * width_ + (width_ - 1)] = last_b;
}
} else {
uint16_t packets = static_cast<uint16_t>(word);
int x = 0;
for (uint16_t pk = 0; pk < packets && cp + 2 <= cdata_len; ++pk) {
x += cd[cp++];
int8_t cnt = static_cast<int8_t>(cd[cp++]);
if (cnt > 0) {
for (int k = 0; k < cnt && cp + 2 <= cdata_len; ++k) {
uint8_t b0 = cd[cp++], b1 = cd[cp++];
if (x < width_) indexed_[static_cast<size_t>(y) * width_ + x] = b0;
if (x + 1 < width_) indexed_[static_cast<size_t>(y) * width_ + x + 1] = b1;
x += 2;
}
} else if (cnt < 0) {
if (cp + 2 > cdata_len) break;
uint8_t b0 = cd[cp++], b1 = cd[cp++];
int run = -cnt;
for (int k = 0; k < run; ++k) {
if (x < width_) indexed_[static_cast<size_t>(y) * width_ + x] = b0;
if (x + 1 < width_) indexed_[static_cast<size_t>(y) * width_ + x + 1] = b1;
x += 2;
}
}
}
++y;
++l;
}
}
}
break;
}
default:
break;
}
pos += std::max<uint32_t>(csize, 6);
}
next_frame_offset_ = offset + fsize;
return true;
}
offset += fsize;
}
return false;
}
} // namespace top_octane::assets
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include "assets/palette.hpp"
#include "core/vfs.hpp"
#include <array>
#include <cstdint>
#include <vector>
namespace top_octane::assets {
// Decodes Bullfrog's DATA/INTRO.DAT (320x200 8-bit FLC variant)
class FlicPlayer {
public:
bool open(const Vfs& vfs, const std::string& path = "DATA/INTRO.DAT");
void reset();
bool step_frame(); // Decodes next frame into current_rgba; returns false at EOF
int width() const { return width_; }
int height() const { return height_; }
int num_frames() const { return num_frames_; }
int current_frame() const { return frame_index_; }
float fps() const { return fps_; }
const std::vector<uint8_t>& rgba() const { return rgba_; }
private:
bool decode_chunk_frame(size_t offset);
std::vector<uint8_t> file_data_;
int width_ = 320;
int height_ = 200;
int num_frames_ = 0;
int frame_index_ = 0;
size_t next_frame_offset_ = 0;
float fps_ = 15.0f;
std::array<Rgba8, 256> palette_{};
std::vector<uint8_t> indexed_;
std::vector<uint8_t> rgba_;
};
} // namespace top_octane::assets
+355
View File
@@ -0,0 +1,355 @@
#include "assets/level.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
namespace top_octane::assets {
namespace {
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
inline int16_t read_le16s(const uint8_t* p) {
return static_cast<int16_t>(read_le16(p));
}
constexpr const char* kTrackNames[6] = {
"1. AMAZON DELTA TURNPIKE",
"2. TRANS-ASIA INTERSTATE",
"3. SHANGHAI DRAGON",
"4. NEW CHERNOBYL CENTRAL",
"5. SLAM CANYON",
"6. THRAK CITY",
};
constexpr size_t kLevelUnpackedSize = 896140;
constexpr size_t kEntitiesOffset = 0x00000;
constexpr size_t kColumnsOffset = 0x17ED8; // 98008
constexpr size_t kBlocksOffset = 0x1E6DC; // 124636
constexpr size_t kMapOffset = 0x62C8C; // 404620
} // namespace
bool LevelData::load(const Vfs& vfs, int level_num) {
level_number = std::clamp(level_num, 1, 6);
world_index = level_number - 1;
name = kTrackNames[world_index];
char rel[64];
std::snprintf(rel, sizeof(rel), "MAPS/LEVEL0-%d.DAT", level_number);
std::vector<uint8_t> raw, data;
if (!vfs.read_file(rel, raw) || !rnc_unpack(raw, data)) {
LOG_ERROR("Failed to load or unpack %s", rel);
return false;
}
if (data.size() != kLevelUnpackedSize) {
LOG_ERROR("Unexpected %s unpacked size: %zu != %zu", rel, data.size(), kLevelUnpackedSize);
return false;
}
// 1. Entities (4000 * 24 bytes)
entities.clear();
entity_slots.resize(kMaxEntities);
pickups.clear();
props.clear();
triggers.clear();
pads.clear();
checkpoints.clear();
std::unordered_map<uint16_t, LevelEntity> wp_map;
std::vector<LevelEntity> raw_gates;
for (int i = 0; i < kMaxEntities; ++i) {
const uint8_t* p = data.data() + kEntitiesOffset + static_cast<size_t>(i) * 24u;
LevelEntity e;
e.id = static_cast<uint16_t>(i);
e.type = p[0];
e.subtype = p[1];
e.group = read_le16(p + 2);
e.target_group = read_le16(p + 4);
e.unk2 = read_le16(p + 6);
e.unk3 = read_le16(p + 8);
e.active_flag = read_le16(p + 10);
e.next_id = read_le16(p + 12);
e.value = read_le16(p + 14);
e.pos_x_fp8 = read_le16(p + 16);
e.pos_z_fp8 = read_le16(p + 18);
e.aux1 = read_le16(p + 20);
e.aux2 = read_le16(p + 22);
entity_slots[i] = e;
if (e.type == 0) continue;
entities.push_back(e);
if (e.type == 1 && e.subtype == 5) {
raw_gates.push_back(e);
} else if (e.type == 3) {
props.push_back(e);
} else if (e.type == 5) {
pickups.push_back(e);
} else if (e.type == 8) {
triggers.push_back(e);
} else if (e.type == 9) {
wp_map[e.id] = e;
} else if (e.type == 10) {
pads.push_back(e);
}
}
// 2. Columns (1024 * 26 bytes)
for (int i = 0; i < kMaxColumns; ++i) {
const uint8_t* p = data.data() + kColumnsOffset + static_cast<size_t>(i) * 26u;
ColumnDefinition& c = columns[i];
c.use_count = read_le16(p + 0);
c.flags = read_le16(p + 2);
c.shape_mask = read_le16(p + 4);
c.floor_tex = read_le16(p + 6);
c.unk = read_le16(p + 8);
for (int b = 0; b < 8; ++b) {
c.blocks[b] = read_le16s(p + 10 + b * 2);
}
}
// 3. Blocks (1024 * 16 bytes)
for (int i = 0; i < kMaxBlocks; ++i) {
const uint8_t* p = data.data() + kBlocksOffset + static_cast<size_t>(i) * 16u;
BlockDefinition& blk = blocks[i];
std::memcpy(blk.tex.data(), p, 6);
std::memcpy(blk.attrs.data(), p + 6, 10);
}
// 4. Map Grid (256 * 160 * 12 bytes)
map.resize(static_cast<size_t>(kMapWidth) * static_cast<size_t>(kMapHeight));
min_x = kMapWidth - 1;
max_x = 0;
min_z = kMapHeight - 1;
max_z = 0;
for (int z = 0; z < kMapHeight; ++z) {
for (int x = 0; x < kMapWidth; ++x) {
size_t idx = static_cast<size_t>(z) * kMapWidth + x;
const uint8_t* p = data.data() + kMapOffset + idx * 12u;
MapEntry& m = map[idx];
m.illumination = read_le16(p + 0);
m.height = read_le16(p + 2);
m.tex_or_col = read_le16s(p + 4);
m.unk3 = read_le16(p + 6);
m.unk4 = read_le16(p + 8);
m.flags = read_le16(p + 10);
if (m.height != 2048 || m.tex_or_col != 0) {
min_x = std::min(min_x, x);
max_x = std::max(max_x, x);
min_z = std::min(min_z, z);
max_z = std::max(max_z, z);
}
}
}
// 5. Extract ordered checkpoints (type 1, subtype 5, ordered by value 0..N-1)
std::sort(raw_gates.begin(), raw_gates.end(),
[](const LevelEntity& a, const LevelEntity& b) { return a.value < b.value; });
for (const auto& g : raw_gates) {
CheckpointGate gate;
gate.index = g.value;
gate.x0 = g.tile_x();
gate.z0 = g.tile_z();
gate.x1 = gate.x0 + static_cast<float>(g.aux1);
gate.z1 = gate.z0 + static_cast<float>(g.aux2);
gate.cx = 0.5f * (gate.x0 + gate.x1);
gate.cz = 0.5f * (gate.z0 + gate.z1);
checkpoints.push_back(gate);
}
// 6. Extract main closed racing waypoint circuit (type == 9 && subtype != 0 cycle)
main_waypoints.clear();
std::vector<uint16_t> best_cycle;
for (const auto& [id, ent] : wp_map) {
if (ent.subtype == 0) continue;
std::vector<uint16_t> path;
std::unordered_map<uint16_t, size_t> seen_pos;
uint16_t cur = id;
while (wp_map.count(cur) && !seen_pos.count(cur)) {
seen_pos[cur] = path.size();
path.push_back(cur);
cur = wp_map[cur].next_id;
}
if (seen_pos.count(cur)) {
std::vector<uint16_t> cyc(path.begin() + static_cast<ptrdiff_t>(seen_pos[cur]), path.end());
if (cyc.size() > best_cycle.size()) {
best_cycle = std::move(cyc);
}
}
}
// Rotate best_cycle so index 0 is the waypoint closest to Checkpoint 0 (Start/Finish)
if (!best_cycle.empty() && !checkpoints.empty()) {
const CheckpointGate& start_gate = checkpoints[0];
size_t best_idx = 0;
float best_dist_sq = 1e18f;
for (size_t i = 0; i < best_cycle.size(); ++i) {
const LevelEntity& wp = wp_map[best_cycle[i]];
float dx = wp.tile_x() - start_gate.cx;
float dz = wp.tile_z() - start_gate.cz;
float d2 = dx * dx + dz * dz;
if (d2 < best_dist_sq) {
best_dist_sq = d2;
best_idx = i;
}
}
std::rotate(best_cycle.begin(), best_cycle.begin() + static_cast<ptrdiff_t>(best_idx), best_cycle.end());
}
main_waypoints.reserve(best_cycle.size());
for (uint16_t wid : best_cycle) {
const LevelEntity& wp = wp_map[wid];
WaypointNode node;
node.entity_id = wid;
node.subtype = wp.subtype;
node.x = wp.tile_x() + 0.5f;
node.z = wp.tile_z() + 0.5f;
node.next_id = wp.next_id;
main_waypoints.push_back(node);
}
// Compute approximate forward vector for each checkpoint from nearest waypoint direction
if (!main_waypoints.empty()) {
for (auto& gate : checkpoints) {
size_t best_wp = 0;
float best_d2 = 1e18f;
for (size_t i = 0; i < main_waypoints.size(); ++i) {
float dx = main_waypoints[i].x - gate.cx;
float dz = main_waypoints[i].z - gate.cz;
float d2 = dx * dx + dz * dz;
if (d2 < best_d2) {
best_d2 = d2;
best_wp = i;
}
}
const WaypointNode& cur_wp = main_waypoints[best_wp];
const WaypointNode& nxt_wp = main_waypoints[(best_wp + 1) % main_waypoints.size()];
Vec2 dir = Vec2(nxt_wp.x - cur_wp.x, nxt_wp.z - cur_wp.z).normalized();
if (dir.len_sq() > 0.01f) {
gate.dir = dir;
}
}
}
return true;
}
const MapEntry& LevelData::cell(int x, int z) const {
x = std::clamp(x, 0, kMapWidth - 1);
z = std::clamp(z, 0, kMapHeight - 1);
return map[static_cast<size_t>(z) * kMapWidth + x];
}
MapEntry& LevelData::cell_mut(int x, int z) {
x = std::clamp(x, 0, kMapWidth - 1);
z = std::clamp(z, 0, kMapHeight - 1);
return map[static_cast<size_t>(z) * kMapWidth + x];
}
float LevelData::cell_height_world(int x, int z) const {
return (static_cast<float>(cell(x, z).height) - kBaseHeight) * kHeightScale;
}
float LevelData::sample_height_world(float wx, float wz) const {
float cx = std::clamp(wx, 0.0f, static_cast<float>(kMapWidth - 1));
float cz = std::clamp(wz, 0.0f, static_cast<float>(kMapHeight - 1));
int x0 = static_cast<int>(cx);
int z0 = static_cast<int>(cz);
int x1 = std::min(x0 + 1, kMapWidth - 1);
int z1 = std::min(z0 + 1, kMapHeight - 1);
float fx = cx - static_cast<float>(x0);
float fz = cz - static_cast<float>(z0);
float h00 = cell_height_world(x0, z0);
float h10 = cell_height_world(x1, z0);
float h01 = cell_height_world(x0, z1);
float h11 = cell_height_world(x1, z1);
float hx0 = h00 + (h10 - h00) * fx;
float hx1 = h01 + (h11 - h01) * fx;
return hx0 + (hx1 - hx0) * fz;
}
Vec3 LevelData::sample_normal_world(float wx, float wz) const {
constexpr float eps = 0.25f;
float hL = sample_height_world(wx - eps, wz);
float hR = sample_height_world(wx + eps, wz);
float hD = sample_height_world(wx, wz - eps);
float hU = sample_height_world(wx, wz + eps);
return Vec3(hL - hR, 2.0f * eps, hD - hU).normalized();
}
bool LevelData::is_cell_solid_at_y(int x, int z, float world_y, float craft_height) const {
if (x < 0 || x >= kMapWidth || z < 0 || z >= kMapHeight) {
return true;
}
const MapEntry& m = cell(x, z);
if (m.tex_or_col >= 0) {
return false;
}
int col_idx = -m.tex_or_col;
if (col_idx <= 0 || col_idx >= kMaxColumns) {
return false;
}
const ColumnDefinition& col = columns[col_idx];
float ground_y = sample_height_world(static_cast<float>(x) + 0.5f, static_cast<float>(z) + 0.5f);
// Blocks stack at slots s = 0..7 spanning [ground_y + s, ground_y + s + 1.0f].
// Test vertical span overlap so crafts drive cleanly under overhead gantries/tunnels
// while riding on column tops when elevated onto bridges.
float min_y = world_y - 0.05f;
float max_y = world_y + craft_height;
for (int s = 0; s < 8; ++s) {
if ((col.shape_mask & (1u << s)) == 0) continue;
float slot_bot = ground_y + static_cast<float>(s);
float slot_top = slot_bot + 1.0f;
if (slot_top > min_y && slot_bot < max_y) {
return true;
}
}
return false;
}
void LevelData::sample_surface_and_ceiling(float wx, float wz, float craft_y,
float& out_floor_y, float& out_ceil_y) const {
out_floor_y = sample_height_world(wx, wz);
out_ceil_y = 1e6f;
int x = static_cast<int>(std::floor(wx));
int z = static_cast<int>(std::floor(wz));
if (x < 0 || x >= kMapWidth || z < 0 || z >= kMapHeight) {
return;
}
const MapEntry& m = cell(x, z);
if (m.tex_or_col >= 0) {
return;
}
int col_idx = -m.tex_or_col;
if (col_idx <= 0 || col_idx >= kMaxColumns) {
return;
}
const ColumnDefinition& col = columns[col_idx];
float ground_y = out_floor_y;
bool grounded_column = (col.shape_mask & 1u) != 0;
for (int s = 0; s < 8; ++s) {
if ((col.shape_mask & (1u << s)) == 0) continue;
float slot_bot = ground_y + static_cast<float>(s);
float slot_top = slot_bot + 1.0f;
if (grounded_column && slot_top <= craft_y + 0.10f) {
out_floor_y = std::max(out_floor_y, slot_top);
}
if (slot_bot >= craft_y + 0.05f) {
out_ceil_y = std::min(out_ceil_y, slot_bot);
}
}
}
} // namespace top_octane::assets
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include "core/math.hpp"
#include "core/vfs.hpp"
#include <array>
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::assets {
constexpr int kMapWidth = 256;
constexpr int kMapHeight = 160;
constexpr int kMaxEntities = 4000;
constexpr int kMaxColumns = 1024;
constexpr int kMaxBlocks = 1024;
struct LevelEntity {
uint16_t id = 0;
uint8_t type = 0;
uint8_t subtype = 0;
uint16_t group = 0;
uint16_t target_group = 0;
uint16_t unk2 = 0;
uint16_t unk3 = 0;
uint16_t active_flag = 0;
uint16_t next_id = 0;
uint16_t value = 0;
uint16_t pos_x_fp8 = 0;
uint16_t pos_z_fp8 = 0;
uint16_t aux1 = 0;
uint16_t aux2 = 0;
float tile_x() const { return static_cast<float>(pos_x_fp8) / 256.0f; }
float tile_z() const { return static_cast<float>(pos_z_fp8) / 256.0f; }
};
struct ColumnDefinition {
uint16_t use_count = 0;
uint16_t flags = 0;
uint16_t shape_mask = 0; // Bits 0..7 indicate populated vertical block levels
uint16_t floor_tex = 0;
uint16_t unk = 0;
std::array<int16_t, 8> blocks{};
};
struct BlockDefinition {
// 6 face textures: 0=North(-Z), 1=East(+X), 2=South(+Z), 3=West(-X), 4=Top(+Y), 5=Bottom(-Y)
std::array<uint8_t, 6> tex{};
// attrs[0..5]: per-face 3-bit UV orientation (bit0=flipU, bit1=flipV, bit2=swapUV)
// attrs[6..7]: 16-bit block use count; attrs[8..9]: reserved
std::array<uint8_t, 10> attrs{};
};
struct MapEntry {
uint16_t illumination = 8192; // 8.8 fixed-point brightness (neutral flat = 8192)
uint16_t height = 2048; // Terrain elevation (sea level baseline = 2048)
int16_t tex_or_col = 0; // >=0: floor tile tex (0..255); <0: column index (-tex_or_col)
uint16_t unk3 = 0;
uint16_t unk4 = 0;
uint16_t flags = 0; // ((flags >> 4) & 7) gives 3-bit dihedral floor tile orientation (bit0=flipU, bit1=flipV, bit2=swapUV)
};
struct CheckpointGate {
uint16_t index = 0;
float x0 = 0.0f, z0 = 0.0f;
float x1 = 0.0f, z1 = 0.0f;
float cx = 0.0f, cz = 0.0f;
Vec2 dir{0.0f, -1.0f}; // approximate track forward direction
};
struct WaypointNode {
uint16_t entity_id = 0;
uint8_t subtype = 0; // 1=corner/slow, 7/8/9/10=normal/fast, 2/3=pit branch
float x = 0.0f;
float z = 0.0f;
uint16_t next_id = 0;
};
struct LevelData {
int level_number = 1; // 1..6
int world_index = 0; // 0..5 (corresponding to TEXTU0-x / SKY0-x / TABLE0-x)
std::string name;
std::vector<LevelEntity> entities; // active non-empty entities
std::vector<LevelEntity> entity_slots; // all 4000 indexed slots
std::array<ColumnDefinition, kMaxColumns> columns{};
std::array<BlockDefinition, kMaxBlocks> blocks{};
std::vector<MapEntry> map; // kMapWidth * kMapHeight
std::vector<WaypointNode> main_waypoints; // ordered main closed circuit
std::vector<CheckpointGate> checkpoints; // ordered val=0..N-1 gates (0 = Start/Finish)
std::vector<LevelEntity> pickups; // type 5
std::vector<LevelEntity> props; // type 3
std::vector<LevelEntity> triggers; // type 8
std::vector<LevelEntity> pads; // type 10
int min_x = 0, max_x = kMapWidth - 1;
int min_z = 0, max_z = kMapHeight - 1;
bool load(const Vfs& vfs, int level_num); // level_num in [1..6]
const MapEntry& cell(int x, int z) const;
MapEntry& cell_mut(int x, int z);
// Height conversion: sea level baseline 2048 -> 0.0 world height; 512 units = 1.0 tile unit (matches ModelMesh)
static constexpr float kHeightScale = 1.0f / 512.0f;
static constexpr float kBaseHeight = 2048.0f;
float cell_height_world(int x, int z) const;
float sample_height_world(float wx, float wz) const;
Vec3 sample_normal_world(float wx, float wz) const;
bool is_cell_solid_at_y(int x, int z, float world_y, float craft_height = 0.42f) const;
void sample_surface_and_ceiling(float wx, float wz, float craft_y,
float& out_floor_y, float& out_ceil_y) const;
};
} // namespace top_octane::assets
+204
View File
@@ -0,0 +1,204 @@
#include "assets/model.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cstring>
namespace top_octane::assets {
namespace {
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
inline int16_t read_le16s(const uint8_t* p) {
return static_cast<int16_t>(read_le16(p));
}
inline uint32_t read_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
} // namespace
bool ObjectTextureAtlas::load(const Vfs& vfs, const Palette& pal,
const std::string& dat_path, const std::string& tab_path) {
std::vector<uint8_t> raw_dat, dat, raw_tab, tab;
if (!vfs.read_file(dat_path, raw_dat) || !rnc_unpack(raw_dat, dat)) {
LOG_ERROR("Failed to read object texture atlas: %s", dat_path.c_str());
return false;
}
if (!vfs.read_file(tab_path, raw_tab) || !rnc_unpack(raw_tab, tab)) {
LOG_ERROR("Failed to read object texture TAB: %s", tab_path.c_str());
return false;
}
width = 256;
if (dat.size() % width != 0 || dat.empty()) {
LOG_ERROR("Invalid object texture atlas size: %zu", dat.size());
return false;
}
height = static_cast<int>(dat.size() / width);
rgba.resize(dat.size() * 4);
for (size_t i = 0; i < dat.size(); ++i) {
uint8_t cidx = dat[i];
const Rgba8& c = pal.colors[cidx];
rgba[i * 4 + 0] = c.r;
rgba[i * 4 + 1] = c.g;
rgba[i * 4 + 2] = c.b;
rgba[i * 4 + 3] = (cidx == 0) ? 0 : 255;
}
entries.clear();
size_t count = tab.size() / 6;
entries.reserve(count);
for (size_t i = 0; i < count; ++i) {
const uint8_t* e = tab.data() + i * 6;
ObjectTexEntry te;
te.offset = read_le32(e);
te.w = e[4];
te.h = e[5];
te.x = static_cast<uint16_t>(te.offset % static_cast<uint32_t>(width));
te.y = static_cast<uint16_t>(te.offset / static_cast<uint32_t>(width));
entries.push_back(te);
}
return true;
}
bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextureAtlas* atlas) {
std::vector<uint8_t> raw, data;
if (!vfs.read_file(path, raw) || !rnc_unpack(raw, data)) {
LOG_ERROR("Failed to read 3D model: %s", path.c_str());
return false;
}
if (data.size() < 58 || std::memcmp(data.data(), "BULLFROG OBJECT DATA", 20) != 0) {
LOG_ERROR("Invalid Bullfrog object header in %s", path.c_str());
return false;
}
name = path;
uint32_t l0 = read_le32(data.data() + 24);
uint32_t l1 = read_le32(data.data() + 28);
uint32_t l2 = read_le32(data.data() + 32);
uint16_t num_faces = read_le16(data.data() + 38);
uint16_t num_verts = read_le16(data.data() + 40);
if (58ull + l0 + l1 + l2 > data.size() || l1 != static_cast<uint32_t>(num_verts) * 6u) {
LOG_ERROR("Invalid chunk sizes in %s (l0=%u l1=%u l2=%u verts=%u)",
path.c_str(), l0, l1, l2, num_verts);
return false;
}
const uint8_t* c0 = data.data() + 58;
const uint8_t* c1 = c0 + l0;
const uint8_t* c2 = c1 + l1;
vertices.resize(num_verts);
bounds_min = Vec3(1e9f, 1e9f, 1e9f);
bounds_max = Vec3(-1e9f, -1e9f, -1e9f);
// Bullfrog model space is Z-up; convert to OpenGL Y-up: (x, z, -y)
// Typical craft width is ~500 raw units; scale 1/512 maps ~1.0 world tile width
constexpr float kModelScale = 1.0f / 512.0f;
for (uint16_t i = 0; i < num_verts; ++i) {
float vx = static_cast<float>(read_le16s(c1 + i * 6 + 0));
float vy = static_cast<float>(read_le16s(c1 + i * 6 + 2));
float vz = static_cast<float>(read_le16s(c1 + i * 6 + 4));
ModelVertex& mv = vertices[i];
mv.raw_pos = Vec3(vx, vy, vz);
mv.pos = Vec3(vx * kModelScale, vz * kModelScale, -vy * kModelScale);
mv.shade = (i < l2) ? c2[i] : 32;
bounds_min.x = std::min(bounds_min.x, mv.pos.x);
bounds_min.y = std::min(bounds_min.y, mv.pos.y);
bounds_min.z = std::min(bounds_min.z, mv.pos.z);
bounds_max.x = std::max(bounds_max.x, mv.pos.x);
bounds_max.y = std::max(bounds_max.y, mv.pos.y);
bounds_max.z = std::max(bounds_max.z, mv.pos.z);
}
if (num_verts == 0) {
bounds_min = bounds_max = Vec3(0, 0, 0);
}
triangles.clear();
triangles.reserve(num_faces);
uint32_t pos = 0;
while (pos < l0) {
uint8_t op = c0[pos];
if (op == 5) {
if (pos + 12 > l0) {
LOG_ERROR("Truncated op5 face in %s", path.c_str());
return false;
}
ModelTriangle tri;
tri.textured = true;
tri.flags = c0[pos + 1];
tri.v[0] = c0[pos + 2];
tri.v[1] = c0[pos + 3];
tri.v[2] = c0[pos + 4];
tri.tex_id = c0[pos + 5];
for (int k = 0; k < 3; ++k) {
if (tri.v[k] >= num_verts) {
LOG_ERROR("Vertex index OOB in %s", path.c_str());
return false;
}
uint8_t px_u = c0[pos + 6 + k * 2 + 0];
uint8_t px_v = c0[pos + 6 + k * 2 + 1];
if (atlas && tri.tex_id < atlas->entries.size()) {
const ObjectTexEntry& te = atlas->entries[tri.tex_id];
if (px_u > te.w || px_v > te.h) {
LOG_WARN("UV out of entry bounds in %s (tex=%u uv=%u,%u wh=%u,%u)",
path.c_str(), tri.tex_id, px_u, px_v, te.w, te.h);
}
tri.u[k] = (static_cast<float>(te.x) + static_cast<float>(px_u)) /
static_cast<float>(atlas->width);
tri.v_coord[k] = (static_cast<float>(te.y) + static_cast<float>(px_v)) /
static_cast<float>(atlas->height);
} else {
tri.u[k] = static_cast<float>(px_u) / 256.0f;
tri.v_coord[k] = static_cast<float>(px_v) / 256.0f;
}
}
triangles.push_back(tri);
pos += 12;
} else if (op == 4) {
if (pos + 6 > l0) {
LOG_ERROR("Truncated op4 face in %s", path.c_str());
return false;
}
ModelTriangle tri;
tri.textured = false;
tri.flags = c0[pos + 1];
tri.v[0] = c0[pos + 2];
tri.v[1] = c0[pos + 3];
tri.v[2] = c0[pos + 4];
tri.pal_color = c0[pos + 5];
for (int k = 0; k < 3; ++k) {
if (tri.v[k] >= num_verts) {
LOG_ERROR("Vertex index OOB in %s", path.c_str());
return false;
}
}
triangles.push_back(tri);
pos += 6;
} else {
LOG_ERROR("Unknown model face opcode %u at %u in %s", op, pos, path.c_str());
return false;
}
}
if (triangles.size() != num_faces) {
LOG_ERROR("Face count mismatch in %s: parsed %zu expected %u",
path.c_str(), triangles.size(), num_faces);
return false;
}
return true;
}
} // namespace top_octane::assets
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include "assets/palette.hpp"
#include "core/math.hpp"
#include "core/vfs.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::assets {
struct ObjectTexEntry {
uint32_t offset = 0;
uint16_t x = 0;
uint16_t y = 0;
uint8_t w = 0;
uint8_t h = 0;
};
struct ObjectTextureAtlas {
int width = 256;
int height = 768;
std::vector<uint8_t> rgba;
std::vector<ObjectTexEntry> entries;
bool load(const Vfs& vfs, const Palette& pal, const std::string& dat_path = "OBJECTS/DATA/TEX0-0.DAT",
const std::string& tab_path = "OBJECTS/DATA/TEX0-0.TAB");
};
struct ModelTriangle {
uint16_t v[3]{};
float u[3]{};
float v_coord[3]{};
uint8_t pal_color = 0;
uint8_t flags = 0;
uint8_t tex_id = 0;
bool textured = false;
};
struct ModelVertex {
Vec3 pos; // Converted to OpenGL Y-up (x, z, -y) in model units
Vec3 raw_pos; // Original Bullfrog (x, y, z)
uint8_t shade = 0;
};
struct ModelMesh {
std::string name;
std::vector<ModelVertex> vertices;
std::vector<ModelTriangle> triangles;
Vec3 bounds_min{0, 0, 0};
Vec3 bounds_max{0, 0, 0};
bool load(const Vfs& vfs, const std::string& path, const ObjectTextureAtlas* atlas = nullptr);
};
} // namespace top_octane::assets
+482
View File
@@ -0,0 +1,482 @@
#include "assets/music_bank.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cctype>
#include <cstring>
namespace top_octane::assets {
namespace {
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
inline int16_t read_le16s(const uint8_t* p) {
return static_cast<int16_t>(read_le16(p));
}
inline uint32_t read_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
inline uint16_t read_be16(const uint8_t* p) {
return static_cast<uint16_t>((static_cast<uint16_t>(p[0]) << 8) | p[1]);
}
inline uint32_t read_be32(const uint8_t* p) {
return (static_cast<uint32_t>(p[0]) << 24) |
(static_cast<uint32_t>(p[1]) << 16) |
(static_cast<uint32_t>(p[2]) << 8) |
static_cast<uint32_t>(p[3]);
}
uint32_t read_vlq(const uint8_t* data, size_t size, size_t& pos) {
uint32_t val = 0;
for (int i = 0; i < 4 && pos < size; ++i) {
uint8_t b = data[pos++];
val = (val << 7) | (b & 0x7Fu);
if ((b & 0x80u) == 0) break;
}
return val;
}
bool starts_with_icase(const std::string& s, const std::string& prefix) {
if (s.size() < prefix.size()) return false;
for (size_t i = 0; i < prefix.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(s[i])) !=
std::tolower(static_cast<unsigned char>(prefix[i]))) {
return false;
}
}
return true;
}
} // namespace
bool MusicArchive::load(const Vfs& vfs, const std::string& path) {
std::vector<uint8_t> raw;
if (!vfs.read_file(path, raw) || raw.size() < 80) {
LOG_ERROR("Failed to read music archive: %s", path.c_str());
return false;
}
uint32_t fat_off = read_le32(raw.data() + raw.size() - 4);
if (fat_off + 8 + 4 * 16 > raw.size()) {
LOG_ERROR("Invalid MUSIC.DAT FAT offset: %u", fat_off);
return false;
}
for (int b = 0; b < 4; ++b) {
size_t bo = static_cast<size_t>(fat_off) + 8u + static_cast<size_t>(b) * 16u;
uint32_t off_fat = read_le32(raw.data() + bo + 0);
uint32_t off_data = read_le32(raw.data() + bo + 4);
uint32_t len_fat = read_le32(raw.data() + bo + 8);
uint32_t len_data = read_le32(raw.data() + bo + 12);
if (off_fat + len_fat > raw.size() || off_data + len_data > raw.size()) {
LOG_ERROR("Out-of-bounds bank %d in MUSIC.DAT", b);
return false;
}
banks[b].clear();
size_t count = len_fat / 32u;
for (size_t i = 1; i < count; ++i) {
const uint8_t* ent = raw.data() + off_fat + i * 32u;
char name_buf[19]{};
std::memcpy(name_buf, ent, 18);
uint32_t s_off = read_le32(ent + 18);
uint32_t s_sz = read_le32(ent + 26);
if (s_off + s_sz > len_data) {
LOG_ERROR("Truncated track %s in MUSIC.DAT bank %d", name_buf, b);
return false;
}
MusicTrackRaw trk;
trk.name = name_buf;
trk.data.assign(raw.data() + off_data + s_off, raw.data() + off_data + s_off + s_sz);
banks[b].push_back(std::move(trk));
}
}
return true;
}
const MusicTrackRaw* MusicArchive::find_track(MusicBankType bank, const std::string& name) const {
const auto& vec = banks[static_cast<size_t>(bank)];
for (const auto& t : vec) {
if (starts_with_icase(t.name, name)) {
return &t;
}
}
return vec.empty() ? nullptr : &vec[0];
}
bool parse_xmi_sequence(const uint8_t* data, size_t size, const std::string& name, XmiSequence& out_seq) {
if (!data || size < 16) return false;
out_seq = XmiSequence{};
out_seq.name = name;
// Locate TIMB (optional) and EVNT chunk inside IFF container (handles FORM/CAT/XMID nesting)
const uint8_t* timb_ptr = nullptr;
uint32_t timb_sz = 0;
const uint8_t* evnt_ptr = nullptr;
uint32_t evnt_sz = 0;
for (size_t i = 0; i + 8 <= size;) {
const uint8_t* id = data + i;
uint32_t csz = read_be32(data + i + 4);
if (std::memcmp(id, "FORM", 4) == 0 || std::memcmp(id, "CAT ", 4) == 0) {
// Enter container header (id + size + 4-byte formType)
if (i + 12 <= size) {
i += 12;
continue;
}
break;
}
if (std::memcmp(id, "TIMB", 4) == 0 && i + 8 + csz <= size) {
timb_ptr = data + i + 8;
timb_sz = csz;
} else if (std::memcmp(id, "EVNT", 4) == 0 && i + 8 + csz <= size) {
evnt_ptr = data + i + 8;
evnt_sz = csz;
break;
}
size_t adv = 8u + csz + (csz & 1u);
if (adv == 0 || i + adv > size) break;
i += adv;
}
if (!evnt_ptr || evnt_sz == 0) {
LOG_ERROR("Missing EVNT chunk in XMIDI sequence %s", name.c_str());
return false;
}
if (timb_ptr && timb_sz >= 2) {
uint16_t cnt = read_le16(timb_ptr);
for (uint16_t i = 0; i < cnt && static_cast<size_t>(2 + i * 2 + 1) < timb_sz; ++i) {
out_seq.timbres.emplace_back(timb_ptr[2 + i * 2], timb_ptr[2 + i * 2 + 1]);
}
}
size_t pos = 0;
uint32_t cur_tick = 0;
uint32_t max_tick = 0;
while (pos < evnt_sz) {
uint8_t b = evnt_ptr[pos];
if (b < 0x80u) {
// XMIDI delta time (bytes < 0x80 summed consecutively)
uint32_t delta = 0;
while (pos < evnt_sz && evnt_ptr[pos] < 0x80u) {
delta += evnt_ptr[pos++];
}
cur_tick += delta;
continue;
}
uint8_t status = evnt_ptr[pos++];
if (status == 0xFFu) {
if (pos >= evnt_sz) break;
uint8_t meta = evnt_ptr[pos++];
uint32_t mlen = read_vlq(evnt_ptr, evnt_sz, pos);
if (meta == 0x2Fu) {
break; // End of track
}
if (meta == 0x51u && mlen == 3 && pos + 3 <= evnt_sz) {
XmiEvent ev;
ev.tick = cur_tick;
ev.status = 0xFFu;
ev.meta_type = meta;
ev.tempo_us = (static_cast<uint32_t>(evnt_ptr[pos]) << 16) |
(static_cast<uint32_t>(evnt_ptr[pos + 1]) << 8) |
static_cast<uint32_t>(evnt_ptr[pos + 2]);
out_seq.events.push_back(ev);
}
pos = std::min<size_t>(evnt_sz, pos + mlen);
continue;
}
if (status == 0xF0u || status == 0xF7u) {
uint32_t slen = read_vlq(evnt_ptr, evnt_sz, pos);
pos = std::min<size_t>(evnt_sz, pos + slen);
continue;
}
uint8_t hi = status & 0xF0u;
if (hi == 0xC0u || hi == 0xD0u) {
if (pos >= evnt_sz) break;
XmiEvent ev;
ev.tick = cur_tick;
ev.status = status;
ev.data1 = evnt_ptr[pos++];
out_seq.events.push_back(ev);
} else if (hi >= 0x80u && hi <= 0xE0u) {
if (pos + 2 > evnt_sz) break;
XmiEvent ev;
ev.tick = cur_tick;
ev.status = status;
ev.data1 = evnt_ptr[pos++];
ev.data2 = evnt_ptr[pos++];
if (hi == 0x90u) {
ev.duration_ticks = read_vlq(evnt_ptr, evnt_sz, pos);
max_tick = std::max(max_tick, cur_tick + ev.duration_ticks);
}
out_seq.events.push_back(ev);
}
max_tick = std::max(max_tick, cur_tick);
}
out_seq.total_ticks = std::max(max_tick, cur_tick);
return !out_seq.events.empty();
}
bool OplTimbreBank::load(const Vfs& vfs, const std::string& path) {
std::vector<uint8_t> data;
if (!vfs.read_file(path, data) || data.size() < 8) {
LOG_ERROR("Failed to load OPL bank: %s", path.c_str());
return false;
}
patches.clear();
for (size_t pos = 0; pos + 6 <= data.size(); pos += 6) {
uint8_t patch = data[pos];
uint8_t bank = data[pos + 1];
if (patch == 0xFFu && bank == 0xFFu) break;
uint32_t off = read_le32(data.data() + pos + 2);
if (off + 14 <= data.size()) {
OplPatch p;
p.patch = patch;
p.bank = bank;
std::memcpy(p.regs.data(), data.data() + off, 14);
patches.push_back(p);
}
}
return !patches.empty();
}
const OplPatch* OplTimbreBank::find(uint8_t patch, uint8_t bank) const {
const OplPatch* bank0_fallback = nullptr;
for (const auto& p : patches) {
if (p.patch == patch && p.bank == bank) return &p;
if (p.patch == patch && p.bank == 0 && !bank0_fallback) bank0_fallback = &p;
}
return bank0_fallback ? bank0_fallback : (patches.empty() ? nullptr : &patches[0]);
}
bool SoundFontBank::load(const Vfs& vfs, const std::string& path) {
std::vector<uint8_t> data;
if (!vfs.read_file(path, data)) {
LOG_ERROR("Failed to read SoundFont: %s", path.c_str());
return false;
}
return load_from_bytes(data.data(), data.size());
}
bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) {
if (!data || size < 12 || std::memcmp(data, "RIFF", 4) != 0 ||
std::memcmp(data + 8, "sfbk", 4) != 0) {
return false;
}
sample_pool.clear();
samples.clear();
presets.clear();
is_sf2 = false;
auto find_subchunk = [&](const char* tag, const uint8_t*& ptr, uint32_t& sz) -> bool {
for (size_t pos = 12; pos + 8 <= size;) {
const uint8_t* cid = data + pos;
uint32_t csz = read_le32(data + pos + 4);
if (std::memcmp(cid, "LIST", 4) == 0) {
pos += 12;
continue;
}
if (std::memcmp(cid, tag, 4) == 0 && pos + 8 + csz <= size) {
ptr = data + pos + 8;
sz = csz;
return true;
}
size_t adv = 8u + csz + (csz & 1u);
if (adv == 0 || pos + adv > size) break;
pos += adv;
}
return false;
};
const uint8_t *ifil_p = nullptr, *smpl_p = nullptr, *snam_p = nullptr;
const uint8_t *phdr_p = nullptr, *pbag_p = nullptr, *pgen_p = nullptr;
const uint8_t *inst_p = nullptr, *ibag_p = nullptr, *igen_p = nullptr, *shdr_p = nullptr;
uint32_t ifil_sz = 0, smpl_sz = 0, snam_sz = 0;
uint32_t phdr_sz = 0, pbag_sz = 0, pgen_sz = 0;
uint32_t inst_sz = 0, ibag_sz = 0, igen_sz = 0, shdr_sz = 0;
if (find_subchunk("ifil", ifil_p, ifil_sz) && ifil_sz >= 4) {
uint16_t major = read_le16(ifil_p);
is_sf2 = (major >= 2);
}
if (!find_subchunk("smpl", smpl_p, smpl_sz) ||
!find_subchunk("phdr", phdr_p, phdr_sz) ||
!find_subchunk("pbag", pbag_p, pbag_sz) ||
!find_subchunk("pgen", pgen_p, pgen_sz) ||
!find_subchunk("inst", inst_p, inst_sz) ||
!find_subchunk("ibag", ibag_p, ibag_sz) ||
!find_subchunk("igen", igen_p, igen_sz) ||
!find_subchunk("shdr", shdr_p, shdr_sz)) {
LOG_ERROR("Missing required SoundFont chunks");
return false;
}
find_subchunk("snam", snam_p, snam_sz);
size_t pool_samples = smpl_sz / 2u;
sample_pool.resize(pool_samples);
for (size_t i = 0; i < pool_samples; ++i) {
sample_pool[i] = read_le16s(smpl_p + i * 2u);
}
// Parse sample headers (SF1 = 16B + snam[20B], SF2 = 46B)
if (is_sf2) {
size_t scnt = shdr_sz / 46u;
for (size_t i = 0; i + 1 < scnt; ++i) {
const uint8_t* p = shdr_p + i * 46u;
char nbuf[21]{};
std::memcpy(nbuf, p, 20);
SoundFontSample s;
s.name = nbuf;
s.start = read_le32(p + 20);
s.end = read_le32(p + 24);
s.loop_start = read_le32(p + 28);
s.loop_end = read_le32(p + 32);
s.sample_rate = read_le32(p + 36);
if (s.sample_rate == 0) s.sample_rate = 44100;
s.root_key = p[40];
s.fine_tune = static_cast<int8_t>(p[41]);
s.in_ram = (s.end <= pool_samples && s.start < s.end);
samples.push_back(std::move(s));
}
} else {
size_t scnt = shdr_sz / 16u;
for (size_t i = 0; i < scnt; ++i) {
const uint8_t* p = shdr_p + i * 16u;
SoundFontSample s;
if (snam_p && (i + 1) * 20u <= snam_sz) {
char nbuf[21]{};
std::memcpy(nbuf, snam_p + i * 20u, 20);
s.name = nbuf;
}
s.start = read_le32(p + 0);
s.end = read_le32(p + 4);
s.loop_start = read_le32(p + 8);
s.loop_end = read_le32(p + 12);
s.sample_rate = 44100;
s.root_key = 60;
s.in_ram = (s.end <= pool_samples && s.start < s.end);
samples.push_back(std::move(s));
}
}
struct RawGen { uint16_t op; uint16_t val; };
auto read_gens = [](const uint8_t* base, uint16_t g0, uint16_t g1, size_t max_bytes) {
std::vector<RawGen> res;
for (uint16_t g = g0; g < g1 && static_cast<size_t>(g + 1) * 4u <= max_bytes; ++g) {
res.push_back({read_le16(base + g * 4u), read_le16(base + g * 4u + 2u)});
}
return res;
};
size_t phdr_cnt = phdr_sz / 38u;
size_t pbag_cnt = pbag_sz / 4u;
size_t inst_cnt = inst_sz / 22u;
size_t ibag_cnt = ibag_sz / 4u;
for (size_t pi = 0; pi + 1 < phdr_cnt; ++pi) {
const uint8_t* p = phdr_p + pi * 38u;
char nbuf[21]{};
std::memcpy(nbuf, p, 20);
SoundFontPreset pr;
pr.name = nbuf;
pr.preset = read_le16(p + 20);
pr.bank = read_le16(p + 22);
uint16_t pb0 = read_le16(p + 24);
uint16_t pb1 = read_le16(phdr_p + (pi + 1) * 38u + 24);
for (uint16_t pb = pb0; pb < pb1 && static_cast<size_t>(pb + 1) < pbag_cnt; ++pb) {
uint16_t pg0 = read_le16(pbag_p + pb * 4u);
uint16_t pg1 = read_le16(pbag_p + (pb + 1) * 4u);
auto pgens = read_gens(pgen_p, pg0, pg1, pgen_sz);
int inst_idx = -1;
for (const auto& g : pgens) {
if (g.op == 41) inst_idx = static_cast<int>(g.val);
}
if (inst_idx < 0 || static_cast<size_t>(inst_idx + 1) >= inst_cnt) continue;
uint16_t ib0 = read_le16(inst_p + inst_idx * 22u + 20);
uint16_t ib1 = read_le16(inst_p + (inst_idx + 1) * 22u + 20);
SoundFontZone global_zone;
for (uint16_t ib = ib0; ib < ib1 && static_cast<size_t>(ib + 1) < ibag_cnt; ++ib) {
uint16_t ig0 = read_le16(ibag_p + ib * 4u);
uint16_t ig1 = read_le16(ibag_p + (ib + 1) * 4u);
auto igens = read_gens(igen_p, ig0, ig1, igen_sz);
SoundFontZone z = global_zone;
for (const auto& g : igens) {
switch (g.op) {
case 43: // keyRange
z.key_lo = static_cast<uint8_t>(g.val & 0xFFu);
z.key_hi = static_cast<uint8_t>((g.val >> 8) & 0xFFu);
break;
case 44: // velRange
z.vel_lo = static_cast<uint8_t>(g.val & 0xFFu);
z.vel_hi = static_cast<uint8_t>((g.val >> 8) & 0xFFu);
break;
case 48: // initialAttenuation (SF2 centibels) or SF1 volume level (0..127)
if (is_sf2) {
z.attenuation_db = static_cast<float>(g.val) * 0.1f;
} else {
float vol = static_cast<float>(std::min<uint16_t>(g.val, 127u));
z.attenuation_db = (127.0f - vol) * 0.375f;
}
break;
case 17: // pan
z.pan_tenths_pct = static_cast<int16_t>(g.val);
break;
case 53: // sampleID
z.sample_id = static_cast<int>(g.val);
break;
case 54: // sampleModes
z.sample_mode = static_cast<int>(g.val & 3u);
break;
case 58: // overridingRootKey
z.root_key_override = static_cast<int>(g.val);
break;
default:
break;
}
}
if (z.sample_id >= 0 && static_cast<size_t>(z.sample_id) < samples.size()) {
pr.zones.push_back(z);
} else if (ib == ib0) {
global_zone = z;
}
}
}
presets.push_back(std::move(pr));
}
return !presets.empty() && !samples.empty();
}
const SoundFontPreset* SoundFontBank::find_preset(uint16_t bank, uint16_t preset) const {
for (const auto& p : presets) {
if (p.bank == bank && p.preset == preset) return &p;
}
return nullptr;
}
} // namespace top_octane::assets
+106
View File
@@ -0,0 +1,106 @@
#pragma once
#include "core/vfs.hpp"
#include <array>
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::assets {
enum class MusicBankType {
GeneralMidi = 0, // .GEN
RolandMt32 = 1, // .ROL
AdlibOpl = 2, // .XMI
Awe32Wt = 3, // .WTB
};
struct XmiEvent {
uint32_t tick = 0; // 120 Hz XMIDI ticks
uint8_t status = 0; // MIDI status byte (0x80..0xEF) or 0xFF meta
uint8_t data1 = 0;
uint8_t data2 = 0;
uint32_t duration_ticks = 0; // For 0x9n note-on events
uint8_t meta_type = 0;
uint32_t tempo_us = 500000; // Set if meta_type == 0x51
};
struct XmiSequence {
std::string name;
std::vector<std::pair<uint8_t, uint8_t>> timbres; // (patch, bank)
std::vector<XmiEvent> events;
uint32_t total_ticks = 0;
};
struct MusicTrackRaw {
std::string name;
std::vector<uint8_t> data; // Raw FORM XDIR...XMID bytes
};
struct MusicArchive {
// 4 banks, each containing 5 songs (TGAME1, TGAME2, TGAME4, TINTRO2, TGAME3)
std::array<std::vector<MusicTrackRaw>, 4> banks;
bool load(const Vfs& vfs, const std::string& path = "SOUND/MUSIC.DAT");
const MusicTrackRaw* find_track(MusicBankType bank, const std::string& name) const;
};
bool parse_xmi_sequence(const uint8_t* data, size_t size, const std::string& name, XmiSequence& out_seq);
struct OplPatch {
uint8_t patch = 0;
uint8_t bank = 0;
std::array<uint8_t, 14> regs{}; // Miles GTL 14-byte OPL timbre
};
struct OplTimbreBank {
std::vector<OplPatch> patches;
bool load(const Vfs& vfs, const std::string& path = "SOUND/SAMPLE.OPL");
const OplPatch* find(uint8_t patch, uint8_t bank) const;
};
struct SoundFontSample {
std::string name;
uint32_t start = 0;
uint32_t end = 0;
uint32_t loop_start = 0;
uint32_t loop_end = 0;
uint32_t sample_rate = 44100;
uint8_t root_key = 60;
int8_t fine_tune = 0;
bool in_ram = false; // false if references external AWE32 ROM
};
struct SoundFontZone {
uint8_t key_lo = 0;
uint8_t key_hi = 127;
uint8_t vel_lo = 0;
uint8_t vel_hi = 127;
int sample_id = -1;
int root_key_override = -1;
int sample_mode = 0; // 0=no loop, 1=continuous loop
float attenuation_db = 0.0f;
int pan_tenths_pct = 0;
};
struct SoundFontPreset {
std::string name;
uint16_t preset = 0;
uint16_t bank = 0;
std::vector<SoundFontZone> zones;
};
struct SoundFontBank {
bool is_sf2 = false;
std::vector<int16_t> sample_pool;
std::vector<SoundFontSample> samples;
std::vector<SoundFontPreset> presets;
bool load(const Vfs& vfs, const std::string& path = "SOUND/BULLFROG.SBK");
bool load_from_bytes(const uint8_t* data, size_t size);
const SoundFontPreset* find_preset(uint16_t bank, uint16_t preset) const;
};
} // namespace top_octane::assets
+83
View File
@@ -0,0 +1,83 @@
#include "assets/palette.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
namespace top_octane::assets {
bool Palette::load(const Vfs& vfs, const std::string& path) {
std::vector<uint8_t> raw, data;
if (!vfs.read_file(path, raw)) {
LOG_ERROR("Failed to read palette: %s", path.c_str());
return false;
}
if (!rnc_unpack(raw, data) || data.size() < 768) {
LOG_ERROR("Invalid palette size in %s: %zu", path.c_str(), data.size());
return false;
}
for (int i = 0; i < 256; ++i) {
// 6-bit VGA DAC (0..63) scaled cleanly to 0..255
uint8_t r6 = std::min<uint8_t>(data[i * 3 + 0], 63);
uint8_t g6 = std::min<uint8_t>(data[i * 3 + 1], 63);
uint8_t b6 = std::min<uint8_t>(data[i * 3 + 2], 63);
colors[i].r = static_cast<uint8_t>((r6 << 2) | (r6 >> 4));
colors[i].g = static_cast<uint8_t>((g6 << 2) | (g6 >> 4));
colors[i].b = static_cast<uint8_t>((b6 << 2) | (b6 >> 4));
colors[i].a = (i == 0) ? 0 : 255;
}
return true;
}
uint8_t Palette::find_nearest(uint8_t r, uint8_t g, uint8_t b) const {
uint8_t best = 0;
int best_dist = 0x7FFFFFFF;
for (int i = 0; i < 256; ++i) {
int dr = int(colors[i].r) - int(r);
int dg = int(colors[i].g) - int(g);
int db = int(colors[i].b) - int(b);
int d = dr * dr + dg * dg + db * db;
if (d < best_dist) {
best_dist = d;
best = static_cast<uint8_t>(i);
}
}
return best;
}
bool ColorTables::load(const Vfs& vfs, int world_index, const Palette& pal) {
char rel[64];
std::snprintf(rel, sizeof(rel), "DATA/TABLE0-%d.DAT", std::clamp(world_index, 0, 5));
std::vector<uint8_t> raw, data;
if (!vfs.read_file(rel, raw)) {
LOG_ERROR("Failed to read color table: %s", rel);
return false;
}
if (!rnc_unpack(raw, data) || data.size() < 83968) {
LOG_ERROR("Invalid color table size in %s: %zu", rel, data.size());
return false;
}
std::memcpy(shade.data(), data.data(), shade.size());
std::memcpy(highlight.data(), data.data() + 0x4000, highlight.size());
std::memcpy(translucency.data(), data.data() + 0x4800, translucency.size());
// Sample row 0 (maximum distance/darkness) across several indices to extract the world's fog tint
uint32_t r_sum = 0, g_sum = 0, b_sum = 0;
constexpr int samples = 16;
for (int i = 0; i < samples; ++i) {
uint8_t idx = shade[i * 16 + 1];
r_sum += pal.colors[idx].r;
g_sum += pal.colors[idx].g;
b_sum += pal.colors[idx].b;
}
fog_color = Vec3(
static_cast<float>(r_sum) / (samples * 255.0f),
static_cast<float>(g_sum) / (samples * 255.0f),
static_cast<float>(b_sum) / (samples * 255.0f)
);
return true;
}
} // namespace top_octane::assets
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "core/math.hpp"
#include "core/vfs.hpp"
#include <array>
#include <cstdint>
namespace top_octane::assets {
struct Rgba8 {
uint8_t r = 0, g = 0, b = 0, a = 255;
};
struct Palette {
std::array<Rgba8, 256> colors{};
bool load(const Vfs& vfs, const std::string& path = "DATA/PALET0-0.DAT");
uint8_t find_nearest(uint8_t r, uint8_t g, uint8_t b) const;
};
struct ColorTables {
// 64 brightness/fog levels (row 0 = darkest / fog, row 63 = full bright)
std::array<uint8_t, 64 * 256> shade{};
std::array<uint8_t, 8 * 256> highlight{};
std::array<uint8_t, 256 * 256> translucency{};
Vec3 fog_color{0.0f, 0.0f, 0.0f};
bool load(const Vfs& vfs, int world_index, const Palette& pal);
uint8_t shade_index(uint8_t level, uint8_t color_idx) const {
return shade[(level & 63u) * 256u + color_idx];
}
};
} // namespace top_octane::assets
+317
View File
@@ -0,0 +1,317 @@
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <array>
#include <cstring>
namespace top_octane::assets {
namespace {
inline uint16_t read_be16(const uint8_t* p) {
return static_cast<uint16_t>((static_cast<uint16_t>(p[0]) << 8) | p[1]);
}
inline uint32_t read_be32(const uint8_t* p) {
return (static_cast<uint32_t>(p[0]) << 24) |
(static_cast<uint32_t>(p[1]) << 16) |
(static_cast<uint32_t>(p[2]) << 8) |
static_cast<uint32_t>(p[3]);
}
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
struct HuffEntry {
uint16_t code;
uint16_t mask;
uint8_t bits;
uint8_t sym;
};
struct Rnc1BitStream {
const uint8_t* src = nullptr;
size_t pos = 0;
uint32_t bitbuf = 0;
int bitcnt = 0;
void init(const uint8_t* buf) {
src = buf;
pos = 0;
bitbuf = read_le16(src);
bitcnt = 16;
}
void advance(int n) {
bitbuf >>= n;
bitcnt -= n;
if (bitcnt < 16) {
pos += 2;
bitbuf |= static_cast<uint32_t>(read_le16(src + pos)) << bitcnt;
bitcnt += 16;
}
}
uint32_t read(uint32_t mask, int n) {
uint32_t v = bitbuf & mask;
advance(n);
return v;
}
void fix() {
bitcnt -= 16;
uint32_t keep_mask = (bitcnt > 0) ? ((1u << bitcnt) - 1u) : 0u;
bitbuf &= keep_mask;
bitbuf |= static_cast<uint32_t>(read_le16(src + pos)) << bitcnt;
bitcnt += 16;
}
};
bool build_huff_table(Rnc1BitStream& bs, std::vector<HuffEntry>& out) {
out.clear();
uint32_t num = bs.read(0x1F, 5);
if (num == 0) return true;
std::array<uint8_t, 32> lens{};
for (uint32_t i = 0; i < num; ++i) {
lens[i] = static_cast<uint8_t>(bs.read(0x0F, 4));
}
uint32_t code = 0;
for (int bl = 1; bl <= 16; ++bl) {
for (uint32_t idx = 0; idx < num; ++idx) {
if (lens[idx] == bl) {
uint16_t rev = 0;
for (int k = 0; k < bl; ++k) {
if (code & (1u << (bl - 1 - k))) {
rev |= static_cast<uint16_t>(1u << k);
}
}
HuffEntry e;
e.code = rev;
e.mask = static_cast<uint16_t>((1u << bl) - 1u);
e.bits = static_cast<uint8_t>(bl);
e.sym = static_cast<uint8_t>(idx);
out.push_back(e);
++code;
}
}
code <<= 1;
}
return true;
}
bool read_huff(Rnc1BitStream& bs, const std::vector<HuffEntry>& tbl, uint32_t& out_val) {
for (const auto& e : tbl) {
if ((bs.bitbuf & e.mask) == e.code) {
bs.advance(e.bits);
if (e.sym < 2) {
out_val = e.sym;
} else {
int extra = e.sym - 1;
uint32_t mask = (1u << extra) - 1u;
out_val = bs.read(mask, extra) | (1u << extra);
}
return true;
}
}
return false;
}
bool unpack_rnc1(const uint8_t* data, size_t size, std::vector<uint8_t>& output) {
if (size < 18) return false;
uint32_t unpacked_len = read_be32(data + 4);
uint32_t packed_len = read_be32(data + 8);
uint16_t unpacked_crc = read_be16(data + 12);
uint16_t packed_crc = read_be16(data + 14);
uint8_t pack_chunks = data[17];
if (18u + packed_len > size) {
LOG_ERROR("RNC1 truncated: need %u, got %zu", 18u + packed_len, size);
return false;
}
if (rnc_crc16(data + 18, packed_len) != packed_crc) {
LOG_ERROR("RNC1 packed CRC16 mismatch");
return false;
}
// Pad with trailing zero bytes so 16-bit prefetch reads safely at end-of-stream
std::vector<uint8_t> src(packed_len + 8, 0);
std::memcpy(src.data(), data + 18, packed_len);
Rnc1BitStream bs;
bs.init(src.data());
bs.read(3, 2); // lock & key bits
output.clear();
output.reserve(unpacked_len);
std::vector<HuffEntry> raw_t, dist_t, len_t;
for (uint8_t chunk = 0; chunk < pack_chunks; ++chunk) {
build_huff_table(bs, raw_t);
build_huff_table(bs, dist_t);
build_huff_table(bs, len_t);
int subchunks = static_cast<int>(bs.read(0xFFFF, 16));
while (true) {
uint32_t raw_len = 0;
if (!read_huff(bs, raw_t, raw_len)) {
LOG_ERROR("RNC1 raw huffman decode failure");
return false;
}
if (raw_len > 0) {
if (bs.pos + raw_len > packed_len + 4) {
LOG_ERROR("RNC1 raw copy OOB");
return false;
}
output.insert(output.end(), src.data() + bs.pos, src.data() + bs.pos + raw_len);
bs.pos += raw_len;
bs.fix();
}
--subchunks;
if (subchunks <= 0) break;
uint32_t dist = 0, mlen = 0;
if (!read_huff(bs, dist_t, dist) || !read_huff(bs, len_t, mlen)) {
LOG_ERROR("RNC1 match huffman decode failure");
return false;
}
dist += 1;
mlen += 2;
if (dist > output.size()) {
LOG_ERROR("RNC1 back-reference OOB: dist=%u size=%zu", dist, output.size());
return false;
}
for (uint32_t k = 0; k < mlen; ++k) {
output.push_back(output[output.size() - dist]);
}
}
}
if (output.size() != unpacked_len) {
LOG_ERROR("RNC1 length mismatch: got %zu expected %u", output.size(), unpacked_len);
return false;
}
if (rnc_crc16(output.data(), output.size()) != unpacked_crc) {
LOG_ERROR("RNC1 unpacked CRC16 mismatch");
return false;
}
return true;
}
// RNC Method 2 decoder (MSB bitstream) supported defensively
bool unpack_rnc2(const uint8_t* data, size_t size, std::vector<uint8_t>& output) {
if (size < 18) return false;
uint32_t unpacked_len = read_be32(data + 4);
uint32_t packed_len = read_be32(data + 8);
uint16_t unpacked_crc = read_be16(data + 12);
uint16_t packed_crc = read_be16(data + 14);
if (18u + packed_len > size) return false;
if (rnc_crc16(data + 18, packed_len) != packed_crc) return false;
const uint8_t* src = data + 18;
size_t pos = 0;
uint16_t bitbuf = 0;
int bitcnt = 0;
auto getbit = [&]() -> int {
if (bitcnt == 0) {
bitbuf = (pos < packed_len) ? src[pos++] : 0;
bitcnt = 8;
}
int bit = (bitbuf >> 7) & 1;
bitbuf <<= 1;
--bitcnt;
return bit;
};
auto getbyte = [&]() -> uint8_t {
return (pos < packed_len) ? src[pos++] : 0;
};
output.clear();
output.reserve(unpacked_len);
getbit();
getbit();
while (true) {
while (getbit() == 0) {
output.push_back(getbyte());
}
uint32_t len = 2;
uint32_t dist = 0;
if (getbit() == 0) {
len = 2;
if (getbit() == 1) {
len += 2;
if (getbit() == 1) len += 1;
}
dist = getbyte() + 1u;
} else {
len = 3;
if (getbit() == 0) {
// raw run of 12..72 bytes
if (getbit() == 0) {
len = 2;
int b0 = getbit(), b1 = getbit(), b2 = getbit();
(void)b0; (void)b1; (void)b2;
// fallback unused by Hi-Octane (which uses RNC1 exclusively)
return false;
}
}
return false;
}
if (dist > output.size()) return false;
for (uint32_t i = 0; i < len; ++i) {
output.push_back(output[output.size() - dist]);
}
if (output.size() >= unpacked_len) break;
}
return output.size() == unpacked_len && rnc_crc16(output.data(), output.size()) == unpacked_crc;
}
} // namespace
uint16_t rnc_crc16(const uint8_t* data, size_t len) {
static const auto table = []() {
std::array<uint16_t, 256> t{};
for (uint16_t i = 0; i < 256; ++i) {
uint16_t v = i;
for (int b = 0; b < 8; ++b) {
v = (v & 1) ? static_cast<uint16_t>((v >> 1) ^ 0xA001u) : static_cast<uint16_t>(v >> 1);
}
t[i] = v;
}
return t;
}();
uint16_t crc = 0;
for (size_t i = 0; i < len; ++i) {
crc ^= data[i];
crc = static_cast<uint16_t>((crc >> 8) ^ table[crc & 0xFFu]);
}
return crc;
}
bool is_rnc_compressed(const std::vector<uint8_t>& input) {
return input.size() >= 18 && input[0] == 'R' && input[1] == 'N' && input[2] == 'C' &&
(input[3] == 1 || input[3] == 2);
}
bool rnc_unpack(const std::vector<uint8_t>& input, std::vector<uint8_t>& output) {
return rnc_unpack_bytes(input.data(), input.size(), output);
}
bool rnc_unpack_bytes(const uint8_t* data, size_t size, std::vector<uint8_t>& output) {
if (!data || size == 0) {
output.clear();
return false;
}
if (size >= 18 && data[0] == 'R' && data[1] == 'N' && data[2] == 'C') {
if (data[3] == 1) return unpack_rnc1(data, size, output);
if (data[3] == 2) return unpack_rnc2(data, size, output);
}
output.assign(data, data + size);
return true;
}
} // namespace top_octane::assets
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <cstdint>
#include <vector>
namespace top_octane::assets {
uint16_t rnc_crc16(const uint8_t* data, size_t len);
// Returns true if buffer starts with "RNC\x01" or "RNC\x02".
bool is_rnc_compressed(const std::vector<uint8_t>& input);
// Decompresses RNC1/RNC2 data, or copies raw data if uncompressed.
bool rnc_unpack(const std::vector<uint8_t>& input, std::vector<uint8_t>& output);
// Convenience raw pointer variant.
bool rnc_unpack_bytes(const uint8_t* data, size_t size, std::vector<uint8_t>& output);
} // namespace top_octane::assets
+216
View File
@@ -0,0 +1,216 @@
#include "assets/sound_bank.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
namespace top_octane::assets {
namespace {
inline uint16_t read_le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(p[1]) << 8));
}
inline int16_t read_le16s(const uint8_t* p) {
return static_cast<int16_t>(read_le16(p));
}
inline uint32_t read_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
bool eq_icase(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
} // namespace
bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) {
if (!data || size < 44 || std::memcmp(data, "RIFF", 4) != 0 ||
std::memcmp(data + 8, "WAVE", 4) != 0) {
return false;
}
uint16_t audio_fmt = 1;
uint16_t channels = 1;
uint32_t sample_rate = 22050;
uint16_t bits_per_sample = 8;
const uint8_t* pcm_ptr = nullptr;
uint32_t pcm_size = 0;
size_t pos = 12;
while (pos + 8 <= size) {
const uint8_t* cid = data + pos;
uint32_t csz = read_le32(data + pos + 4);
pos += 8;
if (pos + csz > size) csz = static_cast<uint32_t>(size - pos);
if (std::memcmp(cid, "fmt ", 4) == 0 && csz >= 16) {
audio_fmt = read_le16(data + pos + 0);
channels = read_le16(data + pos + 2);
sample_rate = read_le32(data + pos + 4);
bits_per_sample = read_le16(data + pos + 14);
} else if (std::memcmp(cid, "data", 4) == 0) {
pcm_ptr = data + pos;
pcm_size = csz;
}
pos += csz + (csz & 1u);
}
if (!pcm_ptr || audio_fmt != 1 || channels == 0 || sample_rate == 0) {
return false;
}
out_sample.sample_rate = static_cast<int>(sample_rate);
out_sample.channels = static_cast<int>(channels);
out_sample.pcm_mono.clear();
if (bits_per_sample == 8) {
size_t frames = pcm_size / channels;
out_sample.pcm_mono.resize(frames);
for (size_t i = 0; i < frames; ++i) {
float sum = 0.0f;
for (uint16_t ch = 0; ch < channels; ++ch) {
sum += (static_cast<float>(pcm_ptr[i * channels + ch]) - 128.0f) / 128.0f;
}
out_sample.pcm_mono[i] = sum / static_cast<float>(channels);
}
} else if (bits_per_sample == 16) {
size_t frames = pcm_size / (2u * channels);
out_sample.pcm_mono.resize(frames);
for (size_t i = 0; i < frames; ++i) {
float sum = 0.0f;
for (uint16_t ch = 0; ch < channels; ++ch) {
sum += static_cast<float>(read_le16s(pcm_ptr + (i * channels + ch) * 2u)) / 32768.0f;
}
out_sample.pcm_mono[i] = sum / static_cast<float>(channels);
}
} else {
return false;
}
if (!out_sample.pcm_mono.empty()) {
double sum_sq = 0.0;
float pk = 0.0f;
for (float x : out_sample.pcm_mono) {
sum_sq += static_cast<double>(x) * static_cast<double>(x);
pk = std::max(pk, std::abs(x));
}
out_sample.rms = static_cast<float>(std::sqrt(sum_sq / static_cast<double>(out_sample.pcm_mono.size())));
out_sample.peak = pk;
} else {
out_sample.rms = 0.0f;
out_sample.peak = 0.0f;
}
return true;
}
bool SoundBank::load(const Vfs& vfs, const std::string& path) {
std::vector<uint8_t> raw;
if (!vfs.read_file(path, raw) || raw.size() < 256) {
LOG_ERROR("Failed to read sound archive: %s", path.c_str());
return false;
}
uint32_t fat_off = read_le32(raw.data() + raw.size() - 4);
if (fat_off + 12 + 10 * 16 > raw.size()) {
LOG_ERROR("Invalid SOUND.DAT tail FAT offset: %u", fat_off);
return false;
}
auto load_bank = [&](int bank_idx, std::vector<SoundSample>& out_list) -> bool {
size_t b_off = static_cast<size_t>(fat_off) + 12u + static_cast<size_t>(bank_idx) * 16u;
uint32_t off_fat = read_le32(raw.data() + b_off + 0);
uint32_t off_data = read_le32(raw.data() + b_off + 4);
uint32_t len_fat = read_le32(raw.data() + b_off + 8);
uint32_t len_data = read_le32(raw.data() + b_off + 12);
if (off_fat == 0xFFFFFFFFu || off_fat + len_fat > raw.size() || off_data >= raw.size()) {
LOG_ERROR("Invalid bank %d offsets in SOUND.DAT", bank_idx);
return false;
}
// Decompress Bank payload once if RNC-packed (Bank 3), else slice directly (Bank 9)
std::vector<uint8_t> unpacked;
const uint8_t* bank_buf = nullptr;
size_t bank_sz = 0;
if (off_data + 18 <= raw.size() && std::memcmp(raw.data() + off_data, "RNC\x01", 4) == 0) {
if (!rnc_unpack_bytes(raw.data() + off_data, raw.size() - off_data, unpacked)) {
LOG_ERROR("Failed to RNC-unpack SOUND.DAT bank %d", bank_idx);
return false;
}
bank_buf = unpacked.data();
bank_sz = unpacked.size();
} else {
if (off_data + len_data > raw.size()) return false;
bank_buf = raw.data() + off_data;
bank_sz = len_data;
}
size_t count = len_fat / 32u;
out_list.clear();
for (size_t i = 1; i < count; ++i) {
const uint8_t* ent = raw.data() + off_fat + i * 32u;
char name_buf[19]{};
std::memcpy(name_buf, ent, 18);
uint32_t s_off = read_le32(ent + 18);
uint32_t s_sz = read_le32(ent + 26);
SoundSample smp;
smp.name = name_buf;
if (s_off + s_sz <= bank_sz && s_sz >= 44) {
if (decode_wav_bytes(bank_buf + s_off, s_sz, smp)) {
// Loudness-normalize 8-bit DOS SFX toward uniform ~0.18 RMS without clipping peaks
if (smp.rms > 1e-4f) {
float g = std::min(std::clamp(0.18f / smp.rms, 0.35f, 1.85f),
0.88f / std::max(smp.peak, 1e-4f));
for (float& x : smp.pcm_mono) {
x = std::clamp(x * g, -0.90f, 0.90f);
}
smp.rms *= g;
smp.peak = std::min(smp.peak * g, 0.90f);
}
} else {
LOG_WARN("Failed to decode WAV %s in SOUND.DAT bank %d", smp.name.c_str(), bank_idx);
}
}
out_list.push_back(std::move(smp));
}
return !out_list.empty();
};
if (!load_bank(3, gameplay_sfx) || !load_bank(9, intro_sfx)) {
return false;
}
return true;
}
const SoundSample* SoundBank::find_gameplay(const std::string& name) const {
for (const auto& s : gameplay_sfx) {
if (eq_icase(s.name, name)) return &s;
}
return nullptr;
}
const SoundSample* SoundBank::find_intro(const std::string& name) const {
for (const auto& s : intro_sfx) {
if (eq_icase(s.name, name)) return &s;
}
return nullptr;
}
} // namespace top_octane::assets
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "core/vfs.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::assets {
struct SoundSample {
std::string name;
int sample_rate = 22050;
int channels = 1;
std::vector<float> pcm_mono; // normalized [-1.0, 1.0]
float rms = 0.0f;
float peak = 0.0f;
};
struct SoundBank {
std::vector<SoundSample> gameplay_sfx; // SOUND.DAT Bank 3 (35 entries, 1..35 mapped 0..34)
std::vector<SoundSample> intro_sfx; // SOUND.DAT Bank 9 (14 entries, 1..14 mapped 0..13)
bool load(const Vfs& vfs, const std::string& path = "SOUND/SOUND.DAT");
const SoundSample* find_gameplay(const std::string& name) const;
const SoundSample* find_intro(const std::string& name) const;
};
// Decodes a RIFF/WAVE buffer into mono float32 PCM
bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample);
} // namespace top_octane::assets
+107
View File
@@ -0,0 +1,107 @@
#include "assets/sprites.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
namespace top_octane::assets {
namespace {
inline uint32_t read_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
} // namespace
bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::string& tab_path,
const Palette& pal) {
std::vector<uint8_t> raw_dat, dat, raw_tab, tab;
if (!vfs.read_file(dat_path, raw_dat) || !rnc_unpack(raw_dat, dat)) {
LOG_ERROR("Failed to load sprite DAT: %s", dat_path.c_str());
return false;
}
if (!vfs.read_file(tab_path, raw_tab) || !rnc_unpack(raw_tab, tab)) {
LOG_ERROR("Failed to load sprite TAB: %s", tab_path.c_str());
return false;
}
size_t count = tab.size() / 6;
sprites.clear();
sprites.resize(count);
for (size_t i = 0; i < count; ++i) {
const uint8_t* entry = tab.data() + i * 6;
uint32_t off = read_le32(entry);
int w = entry[4];
int h = entry[5];
SpriteImage& img = sprites[i];
img.width = w;
img.height = h;
if (w <= 0 || h <= 0 || off >= dat.size()) {
continue;
}
img.rgba.assign(static_cast<size_t>(w) * static_cast<size_t>(h) * 4u, 0);
size_t p = off;
int x = 0;
int y = 0;
while (y < h && p < dat.size()) {
int8_t code = static_cast<int8_t>(dat[p++]);
if (code == 0) {
++y;
x = 0;
} else if (code > 0) {
int run = code;
if (p + static_cast<size_t>(run) > dat.size()) {
LOG_ERROR("Sprite RLE literal OOB in %s[%zu]", dat_path.c_str(), i);
return false;
}
for (int k = 0; k < run; ++k) {
uint8_t idx = dat[p++];
if (x >= 0 && x < w) {
const Rgba8& c = pal.colors[idx];
size_t dst = (static_cast<size_t>(y) * w + x) * 4u;
img.rgba[dst + 0] = c.r;
img.rgba[dst + 1] = c.g;
img.rgba[dst + 2] = c.b;
img.rgba[dst + 3] = 255;
}
++x;
}
} else {
x += -code;
}
}
}
return true;
}
bool load_raw_screen(const Vfs& vfs, const std::string& path, int width, int height,
const Palette& pal, SpriteImage& out_img) {
std::vector<uint8_t> raw, data;
if (!vfs.read_file(path, raw) || !rnc_unpack(raw, data)) {
LOG_ERROR("Failed to load raw screen: %s", path.c_str());
return false;
}
size_t expected = static_cast<size_t>(width) * static_cast<size_t>(height);
if (data.size() < expected) {
LOG_ERROR("Raw screen %s too small: %zu < %zu", path.c_str(), data.size(), expected);
return false;
}
out_img.width = width;
out_img.height = height;
out_img.rgba.resize(expected * 4u);
for (size_t i = 0; i < expected; ++i) {
const Rgba8& c = pal.colors[data[i]];
out_img.rgba[i * 4 + 0] = c.r;
out_img.rgba[i * 4 + 1] = c.g;
out_img.rgba[i * 4 + 2] = c.b;
out_img.rgba[i * 4 + 3] = 255;
}
return true;
}
} // namespace top_octane::assets
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "assets/palette.hpp"
#include "core/vfs.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::assets {
struct SpriteImage {
int width = 0;
int height = 0;
std::vector<uint8_t> rgba; // width * height * 4
};
struct SpriteBank {
std::vector<SpriteImage> sprites;
bool load(const Vfs& vfs, const std::string& dat_path, const std::string& tab_path,
const Palette& pal);
};
// Loads a raw indexed full-screen image (e.g., TITLE.DAT 320x200 or OSCR0-1.DAT 640x480)
bool load_raw_screen(const Vfs& vfs, const std::string& path, int width, int height,
const Palette& pal, SpriteImage& out_img);
} // namespace top_octane::assets
+56
View File
@@ -0,0 +1,56 @@
#include "assets/textures.hpp"
#include "assets/rnc.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cstdio>
namespace top_octane::assets {
bool WorldTextures::load(const Vfs& vfs, int world_index, const Palette& pal) {
int idx = std::clamp(world_index, 0, 5);
char tex_path[64], sky_path[64];
std::snprintf(tex_path, sizeof(tex_path), "DATA/TEXTU0-%d.DAT", idx);
std::snprintf(sky_path, sizeof(sky_path), "DATA/SKY0-%d.DAT", idx);
std::vector<uint8_t> raw_tex;
if (!vfs.read_file(tex_path, raw_tex) || !rnc_unpack(raw_tex, tile_indices)) {
LOG_ERROR("Failed to load texture pack: %s", tex_path);
return false;
}
if (tile_indices.size() != static_cast<size_t>(kTileCount * kTileSize * kTileSize)) {
LOG_ERROR("Unexpected %s size: %zu", tex_path, tile_indices.size());
return false;
}
tile_rgba.resize(tile_indices.size() * 4);
for (size_t i = 0; i < tile_indices.size(); ++i) {
const Rgba8& c = pal.colors[tile_indices[i]];
tile_rgba[i * 4 + 0] = c.r;
tile_rgba[i * 4 + 1] = c.g;
tile_rgba[i * 4 + 2] = c.b;
tile_rgba[i * 4 + 3] = 255; // terrain tiles are opaque
}
std::vector<uint8_t> raw_sky, sky_indices;
if (!vfs.read_file(sky_path, raw_sky) || !rnc_unpack(raw_sky, sky_indices)) {
LOG_ERROR("Failed to load sky texture: %s", sky_path);
return false;
}
if (sky_indices.size() != static_cast<size_t>(kSkySize * kSkySize)) {
LOG_ERROR("Unexpected %s size: %zu", sky_path, sky_indices.size());
return false;
}
sky_rgba.resize(sky_indices.size() * 4);
for (size_t i = 0; i < sky_indices.size(); ++i) {
const Rgba8& c = pal.colors[sky_indices[i]];
sky_rgba[i * 4 + 0] = c.r;
sky_rgba[i * 4 + 1] = c.g;
sky_rgba[i * 4 + 2] = c.b;
sky_rgba[i * 4 + 3] = 255;
}
return true;
}
} // namespace top_octane::assets
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "assets/palette.hpp"
#include "core/vfs.hpp"
#include <cstdint>
#include <vector>
namespace top_octane::assets {
struct WorldTextures {
static constexpr int kTileSize = 64;
static constexpr int kTileCount = 256;
static constexpr int kSkySize = 256;
// 256 contiguous 64x64 RGBA8 tiles (256 * 64 * 64 * 4 bytes) for GL_TEXTURE_2D_ARRAY
std::vector<uint8_t> tile_rgba;
std::vector<uint8_t> tile_indices; // raw 8-bit palette indices (256 * 64 * 64)
std::vector<uint8_t> sky_rgba; // 256x256 RGBA8 skybox texture
bool load(const Vfs& vfs, int world_index, const Palette& pal);
};
} // namespace top_octane::assets
+491
View File
@@ -0,0 +1,491 @@
#include "audio/audio_engine.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
namespace top_octane::audio {
namespace {
int map_track_slot(MusicTrackId id) {
// MUSIC.DAT ordering: 0=TGAME1, 1=TGAME2, 2=TGAME4, 3=TINTRO2, 4=TGAME3
switch (id) {
case MusicTrackId::Game1: return 0;
case MusicTrackId::Game2: return 1;
case MusicTrackId::Game4: return 2;
case MusicTrackId::TitleIntro: return 3;
case MusicTrackId::Game3: return 4;
}
return 0;
}
const char* track_stem(MusicTrackId id) {
switch (id) {
case MusicTrackId::TitleIntro: return "tintro2";
case MusicTrackId::Game1: return "tgame1";
case MusicTrackId::Game2: return "tgame2";
case MusicTrackId::Game3: return "tgame3";
case MusicTrackId::Game4: return "tgame4";
}
return "tgame1";
}
bool eq_icase(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
} // namespace
AudioEngine::~AudioEngine() {
shutdown();
}
bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device) {
if (initialized_) return true;
if (!sound_bank_.load(vfs) || !music_archive_.load(vfs) ||
!opl_bank_.load(vfs) || !sf_bank_.load(vfs)) {
return false;
}
// Pre-parse all 5 tracks for OPL3 (.XMI bank 2) and SoundFont (.WTB bank 3)
for (int i = 0; i < 5; ++i) {
const auto& xmi_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::AdlibOpl)][i];
assets::parse_xmi_sequence(xmi_raw.data.data(), xmi_raw.data.size(), xmi_raw.name, opl_seqs_[i]);
const auto& wtb_raw = music_archive_.banks[static_cast<size_t>(assets::MusicBankType::Awe32Wt)][i];
assets::parse_xmi_sequence(wtb_raw.data.data(), wtb_raw.data.size(), wtb_raw.name, wt_seqs_[i]);
}
// Optional external SoundFont (.sf2)
has_custom_sf_ = false;
if (!cfg.custom_soundfont_path.empty()) {
std::vector<uint8_t> sf_bytes;
if (Vfs::read_raw_file(cfg.custom_soundfont_path, sf_bytes) &&
custom_sf_bank_.load_from_bytes(sf_bytes.data(), sf_bytes.size())) {
has_custom_sf_ = true;
}
}
// Optional custom WAV music tracks in <pref_dir>/music/*.wav
for (int i = 0; i < 5; ++i) {
MusicTrackId tid = static_cast<MusicTrackId>(i);
std::filesystem::path wp = vfs.pref_dir() / "music" / (std::string(track_stem(tid)) + ".wav");
std::vector<uint8_t> wdata;
if (Vfs::read_raw_file(wp, wdata)) {
assets::decode_wav_bytes(wdata.data(), wdata.size(), custom_wav_tracks_[i]);
}
}
opl_synth_.set_timbre_bank(&opl_bank_);
opl_synth_.set_sample_rate(kSampleRate);
sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_);
sf_synth_.set_opl_fallback(&opl_bank_);
sf_synth_.set_sample_rate(kSampleRate);
xmi_player_.set_sample_rate(kSampleRate);
engine_sample_ = sound_bank_.find_gameplay("ENGINE1.WAV");
if (!engine_sample_) engine_sample_ = sound_bank_.find_gameplay("TESTENG3.WAV");
scrape_sample_ = sound_bank_.find_gameplay("SCRAPE2.WAV");
active_backend_ = cfg.music_backend;
requested_backend_ = cfg.music_backend;
master_vol_.store(cfg.master_volume, std::memory_order_relaxed);
sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed);
music_vol_.store(cfg.music_volume, std::memory_order_relaxed);
mix_sample_clock_ = static_cast<uint64_t>(kSampleRate) * 60ull;
voice_seq_ = 0;
last_play_sample_gameplay_.fill(0);
last_play_sample_intro_.fill(0);
for (auto& v : sfx_voices_) v = SfxVoice{};
if (open_device) {
if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
LOG_WARN("SDL audio init failed (%s); continuing silent", SDL_GetError());
}
}
if (SDL_WasInit(SDL_INIT_AUDIO) != 0) {
SDL_AudioSpec want{}, have{};
want.freq = kSampleRate;
want.format = AUDIO_F32SYS;
want.channels = 2;
want.samples = 1024;
want.callback = &AudioEngine::sdl_audio_callback;
want.userdata = this;
dev_id_ = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0);
if (dev_id_ == 0) {
LOG_WARN("SDL_OpenAudioDevice failed (%s); continuing silent", SDL_GetError());
} else {
SDL_PauseAudioDevice(dev_id_, 0);
LOG_INFO("SDL2 Audio opened: %d Hz, float32 stereo", have.freq);
}
}
}
initialized_ = true;
return true;
}
void AudioEngine::shutdown() {
if (!initialized_) return;
if (dev_id_ != 0) {
SDL_CloseAudioDevice(dev_id_);
dev_id_ = 0;
}
initialized_ = false;
}
void AudioEngine::apply_config(const GameConfig& cfg, bool window_focused) {
master_vol_.store(cfg.master_volume, std::memory_order_relaxed);
sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed);
music_vol_.store(cfg.music_volume, std::memory_order_relaxed);
muted_.store(cfg.mute_on_focus_loss && !window_focused, std::memory_order_relaxed);
if (cfg.music_backend != requested_backend_) {
requested_backend_ = cfg.music_backend;
AudioCommand cmd;
cmd.type = CmdType::SetBackend;
cmd.backend = cfg.music_backend;
push_command(cmd);
}
}
void AudioEngine::play_music(MusicTrackId track, bool loop) {
AudioCommand cmd;
cmd.type = CmdType::PlayMusic;
cmd.track = track;
cmd.loop = loop;
push_command(cmd);
}
void AudioEngine::stop_music() {
AudioCommand cmd;
cmd.type = CmdType::StopMusic;
push_command(cmd);
}
int AudioEngine::find_sfx_index(const std::string& name, bool intro_bank) const {
const auto& vec = intro_bank ? sound_bank_.intro_sfx : sound_bank_.gameplay_sfx;
for (size_t i = 0; i < vec.size(); ++i) {
if (eq_icase(vec[i].name, name)) return static_cast<int>(i);
}
return -1;
}
void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch,
float pan, bool is_intro_bank, float min_interval_sec) {
int idx = find_sfx_index(wav_name, is_intro_bank);
if (idx < 0 && is_intro_bank) {
is_intro_bank = false;
idx = find_sfx_index(wav_name, false);
}
if (idx < 0) return;
AudioCommand cmd;
cmd.type = CmdType::PlaySfx;
cmd.sample_idx = idx;
cmd.intro_bank = is_intro_bank;
cmd.gain = std::clamp(gain, 0.0f, 2.0f);
cmd.pitch = std::clamp(pitch, 0.25f, 3.0f);
cmd.pan = std::clamp(pan, -1.0f, 1.0f);
cmd.min_interval_sec = std::max(0.0f, min_interval_sec);
push_command(cmd);
}
void AudioEngine::play_sfx_3d(const std::string& wav_name, const Vec3& src_pos,
const Vec3& listener_pos, const Vec3& listener_right,
float gain, float pitch, float min_interval_sec) {
Vec3 d = src_pos - listener_pos;
float dist = d.len();
if (dist > 28.0f) return;
float atten = 1.0f / (1.0f + dist * 0.22f + dist * dist * 0.025f);
float pan = (dist > 0.1f) ? std::clamp((d / dist).dot(listener_right), -1.0f, 1.0f) : 0.0f;
play_sfx(wav_name, gain * atten, pitch, pan, false, min_interval_sec);
}
void AudioEngine::set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount) {
engine_active_.store(active, std::memory_order_relaxed);
engine_speed_ratio_.store(std::clamp(speed_ratio, 0.0f, 1.5f), std::memory_order_relaxed);
engine_boosting_.store(boosting, std::memory_order_relaxed);
scrape_amount_.store(std::clamp(scrape_amount, 0.0f, 1.0f), std::memory_order_relaxed);
}
const assets::XmiSequence& AudioEngine::xmi_sequence(MusicBackend b, MusicTrackId t) const {
int slot = map_track_slot(t);
return (b == MusicBackend::SoundFont) ? wt_seqs_[slot] : opl_seqs_[slot];
}
bool AudioEngine::push_command(const AudioCommand& cmd) {
uint32_t head = cmd_head_.load(std::memory_order_relaxed);
uint32_t next = (head + 1u) % kCmdQueueSize;
if (next == cmd_tail_.load(std::memory_order_acquire)) {
return false; // full
}
cmd_ring_[head] = cmd;
cmd_head_.store(next, std::memory_order_release);
return true;
}
void AudioEngine::drain_commands() {
uint32_t tail = cmd_tail_.load(std::memory_order_relaxed);
uint32_t head = cmd_head_.load(std::memory_order_acquire);
while (tail != head) {
const AudioCommand& cmd = cmd_ring_[tail];
switch (cmd.type) {
case CmdType::PlaySfx: {
const auto& vec = cmd.intro_bank ? sound_bank_.intro_sfx : sound_bank_.gameplay_sfx;
if (cmd.sample_idx >= 0 && static_cast<size_t>(cmd.sample_idx) < vec.size()) {
const assets::SoundSample* smp = &vec[cmd.sample_idx];
if (smp->pcm_mono.empty()) break;
auto& last_arr = cmd.intro_bank ? last_play_sample_intro_ : last_play_sample_gameplay_;
if (static_cast<size_t>(cmd.sample_idx) < last_arr.size()) {
uint64_t min_samples = static_cast<uint64_t>(cmd.min_interval_sec * static_cast<float>(kSampleRate));
if (mix_sample_clock_ - last_arr[cmd.sample_idx] < min_samples) {
break;
}
last_arr[cmd.sample_idx] = mix_sample_clock_;
}
int same_count = 0;
SfxVoice* oldest_same = nullptr;
SfxVoice* free_slot = nullptr;
SfxVoice* oldest_any = nullptr;
for (auto& v : sfx_voices_) {
if (!v.active) {
if (!free_slot) free_slot = &v;
continue;
}
if (!oldest_any || v.start_seq < oldest_any->start_seq) {
oldest_any = &v;
}
if (v.sample_idx == cmd.sample_idx && v.intro_bank == cmd.intro_bank) {
++same_count;
if (!oldest_same || v.start_seq < oldest_same->start_seq) {
oldest_same = &v;
}
}
}
SfxVoice* target = (same_count >= kMaxSameSampleVoices && oldest_same)
? oldest_same
: (free_slot ? free_slot : oldest_any);
if (target) {
target->active = true;
target->sample = smp;
target->sample_idx = cmd.sample_idx;
target->intro_bank = cmd.intro_bank;
target->start_seq = ++voice_seq_;
target->pos = 0.0;
target->step = (static_cast<double>(smp->sample_rate) / kSampleRate) * cmd.pitch;
target->gain_l = cmd.gain * std::sqrt(0.5f * (1.0f - cmd.pan));
target->gain_r = cmd.gain * std::sqrt(0.5f * (1.0f + cmd.pan));
}
}
break;
}
case CmdType::PlayMusic: {
active_track_ = cmd.track;
active_loop_ = cmd.loop;
int slot = map_track_slot(cmd.track);
opl_synth_.all_notes_off();
sf_synth_.all_notes_off();
custom_music_playing_ = false;
custom_music_pos_ = 0.0;
if (active_backend_ == MusicBackend::Custom &&
!custom_wav_tracks_[static_cast<int>(cmd.track)].pcm_mono.empty()) {
xmi_player_.stop();
custom_music_playing_ = true;
} else if (active_backend_ == MusicBackend::SoundFont) {
xmi_player_.set_sequence(&wt_seqs_[slot], cmd.loop);
} else {
xmi_player_.set_sequence(&opl_seqs_[slot], cmd.loop);
}
break;
}
case CmdType::StopMusic:
xmi_player_.stop();
opl_synth_.all_notes_off();
sf_synth_.all_notes_off();
custom_music_playing_ = false;
break;
case CmdType::SetBackend:
if (cmd.backend != active_backend_) {
bool was_playing = xmi_player_.is_playing() || custom_music_playing_;
active_backend_ = cmd.backend;
opl_synth_.all_notes_off();
sf_synth_.all_notes_off();
custom_music_playing_ = false;
if (was_playing) {
int slot = map_track_slot(active_track_);
if (active_backend_ == MusicBackend::Custom &&
!custom_wav_tracks_[static_cast<int>(active_track_)].pcm_mono.empty()) {
xmi_player_.stop();
custom_music_playing_ = true;
custom_music_pos_ = 0.0;
} else if (active_backend_ == MusicBackend::SoundFont) {
xmi_player_.set_sequence(&wt_seqs_[slot], active_loop_);
} else {
xmi_player_.set_sequence(&opl_seqs_[slot], active_loop_);
}
}
}
break;
}
tail = (tail + 1u) % kCmdQueueSize;
}
cmd_tail_.store(tail, std::memory_order_release);
}
void AudioEngine::render_internal(float* stereo_out, int frames) {
if (frames <= 0) return;
std::memset(stereo_out, 0, static_cast<size_t>(frames) * 2u * sizeof(float));
drain_commands();
const float master = muted_.load(std::memory_order_relaxed) ? 0.0f : master_vol_.load(std::memory_order_relaxed);
const float mvol = music_vol_.load(std::memory_order_relaxed) * master;
const float svol = sfx_vol_.load(std::memory_order_relaxed) * master;
constexpr int kChunk = 512;
std::array<float, kChunk * 2> sfx_bus;
for (int off = 0; off < frames; off += kChunk) {
int cur = std::min(kChunk, frames - off);
float* out_ptr = stereo_out + off * 2;
// 1. Render Music into output chunk
if (mvol > 0.001f) {
if (custom_music_playing_) {
const auto& tr = custom_wav_tracks_[static_cast<int>(active_track_)];
if (!tr.pcm_mono.empty()) {
double step = static_cast<double>(tr.sample_rate) / kSampleRate;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(custom_music_pos_);
if (i0 + 1 >= tr.pcm_mono.size()) {
if (active_loop_) {
custom_music_pos_ = 0.0;
i0 = 0;
} else {
custom_music_playing_ = false;
break;
}
}
float s = tr.pcm_mono[i0] * mvol;
out_ptr[f * 2 + 0] += s;
out_ptr[f * 2 + 1] += s;
custom_music_pos_ += step;
}
}
} else if (xmi_player_.is_playing()) {
if (active_backend_ == MusicBackend::SoundFont) {
xmi_player_.render(out_ptr, cur, sf_synth_);
} else {
xmi_player_.render(out_ptr, cur, opl_synth_);
}
for (int i = 0; i < cur * 2; ++i) {
out_ptr[i] *= mvol;
}
}
}
// 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft compressor
if (svol > 0.001f) {
std::fill_n(sfx_bus.data(), cur * 2, 0.0f);
for (auto& v : sfx_voices_) {
if (!v.active || !v.sample) continue;
const auto& pcm = v.sample->pcm_mono;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(v.pos);
if (i0 + 1 >= pcm.size()) {
v.active = false;
break;
}
float frac = static_cast<float>(v.pos - static_cast<double>(i0));
float s = (pcm[i0] + (pcm[i0 + 1] - pcm[i0]) * frac) * svol;
sfx_bus[f * 2 + 0] += s * v.gain_l;
sfx_bus[f * 2 + 1] += s * v.gain_r;
v.pos += v.step;
}
}
if (engine_active_.load(std::memory_order_relaxed) && engine_sample_ &&
!engine_sample_->pcm_mono.empty()) {
float spd = engine_speed_ratio_.load(std::memory_order_relaxed);
bool bst = engine_boosting_.load(std::memory_order_relaxed);
double pitch = 0.65 + 0.65 * spd + (bst ? 0.28 : 0.0);
double step = (static_cast<double>(engine_sample_->sample_rate) / kSampleRate) * pitch;
float egain = (0.13f + 0.11f * std::min(spd, 1.0f)) * svol;
const auto& pcm = engine_sample_->pcm_mono;
size_t len = pcm.size();
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(engine_pos_) % len;
size_t i1 = (i0 + 1) % len;
float frac = static_cast<float>(engine_pos_ - std::floor(engine_pos_));
float s = (pcm[i0] + (pcm[i1] - pcm[i0]) * frac) * egain;
sfx_bus[f * 2 + 0] += s;
sfx_bus[f * 2 + 1] += s;
engine_pos_ += step;
if (engine_pos_ >= static_cast<double>(len)) {
engine_pos_ -= static_cast<double>(len);
}
}
}
float scrape = scrape_amount_.load(std::memory_order_relaxed);
if (scrape > 0.02f && scrape_sample_ && !scrape_sample_->pcm_mono.empty()) {
const auto& pcm = scrape_sample_->pcm_mono;
size_t len = pcm.size();
double step = static_cast<double>(scrape_sample_->sample_rate) / kSampleRate;
float sgain = scrape * 0.22f * svol;
for (int f = 0; f < cur; ++f) {
size_t i0 = static_cast<size_t>(scrape_pos_) % len;
float s = pcm[i0] * sgain;
sfx_bus[f * 2 + 0] += s;
sfx_bus[f * 2 + 1] += s;
scrape_pos_ += step;
if (scrape_pos_ >= static_cast<double>(len)) scrape_pos_ -= static_cast<double>(len);
}
}
for (int i = 0; i < cur * 2; ++i) {
out_ptr[i] += std::tanh(sfx_bus[i] * 1.1f) * 0.88f;
}
}
}
mix_sample_clock_ += static_cast<uint64_t>(frames);
// Outer soft limiter against clipping
for (int i = 0; i < frames * 2; ++i) {
float x = stereo_out[i];
if (x > 0.96f || x < -0.96f) {
stereo_out[i] = std::tanh(x) * 0.985f;
}
}
}
void AudioEngine::mix_offline(float* stereo_out, int frames) {
render_internal(stereo_out, frames);
}
void AudioEngine::sdl_audio_callback(void* userdata, uint8_t* stream, int len) {
auto* self = static_cast<AudioEngine*>(userdata);
int frames = len / static_cast<int>(sizeof(float) * 2);
self->render_internal(reinterpret_cast<float*>(stream), frames);
}
} // namespace top_octane::audio
+160
View File
@@ -0,0 +1,160 @@
#pragma once
#include "assets/music_bank.hpp"
#include "assets/sound_bank.hpp"
#include "audio/opl3_synth.hpp"
#include "audio/sf_synth.hpp"
#include "audio/xmidi_player.hpp"
#include "core/config.hpp"
#include "core/math.hpp"
#include "core/vfs.hpp"
#include <SDL.h>
#include <array>
#include <atomic>
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::audio {
enum class MusicTrackId {
TitleIntro = 0, // TINTRO2
Game1 = 1, // TGAME1
Game2 = 2, // TGAME2
Game3 = 3, // TGAME3
Game4 = 4, // TGAME4
};
class AudioEngine {
public:
static constexpr int kSampleRate = 48000;
static constexpr int kMaxSfxVoices = 32;
static constexpr int kMaxSameSampleVoices = 3;
static constexpr int kCmdQueueSize = 256;
AudioEngine() = default;
~AudioEngine();
AudioEngine(const AudioEngine&) = delete;
AudioEngine& operator=(const AudioEngine&) = delete;
// Loads assets (SOUND.DAT, MUSIC.DAT, SAMPLE.OPL, BULLFROG.SBK) & opens SDL audio if open_device==true
bool init(const Vfs& vfs, const GameConfig& cfg, bool open_device = true);
void shutdown();
void apply_config(const GameConfig& cfg, bool window_focused = true);
void play_music(MusicTrackId track, bool loop = true);
void stop_music();
// Gameplay / intro SFX triggers (thread-safe lock-free push)
void play_sfx(const std::string& wav_name, float gain = 1.0f, float pitch = 1.0f,
float pan = 0.0f, bool is_intro_bank = false, float min_interval_sec = 0.05f);
void play_sfx_3d(const std::string& wav_name, const Vec3& src_pos,
const Vec3& listener_pos, const Vec3& listener_right,
float gain = 1.0f, float pitch = 1.0f, float min_interval_sec = 0.05f);
// Continuous player engine pitch/volume modulation
void set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount);
// Offline render hook for deterministic unit testing
void mix_offline(float* stereo_out, int frames);
const assets::SoundBank& sound_bank() const { return sound_bank_; }
const assets::OplTimbreBank& opl_bank() const { return opl_bank_; }
const assets::SoundFontBank& sf_bank() const { return sf_bank_; }
const assets::XmiSequence& xmi_sequence(MusicBackend b, MusicTrackId t) const;
private:
enum class CmdType : uint8_t {
PlaySfx = 0,
PlayMusic,
StopMusic,
SetBackend,
};
struct AudioCommand {
CmdType type = CmdType::PlaySfx;
int sample_idx = -1;
bool intro_bank = false;
float gain = 1.0f;
float pitch = 1.0f;
float pan = 0.0f;
float min_interval_sec = 0.05f;
MusicTrackId track = MusicTrackId::Game1;
bool loop = true;
MusicBackend backend = MusicBackend::Opl3;
};
struct SfxVoice {
bool active = false;
const assets::SoundSample* sample = nullptr;
int sample_idx = -1;
bool intro_bank = false;
uint64_t start_seq = 0;
double pos = 0.0;
double step = 1.0;
float gain_l = 0.0f;
float gain_r = 0.0f;
};
bool push_command(const AudioCommand& cmd);
void drain_commands();
void render_internal(float* stereo_out, int frames);
int find_sfx_index(const std::string& name, bool intro_bank) const;
static void sdl_audio_callback(void* userdata, uint8_t* stream, int len);
SDL_AudioDeviceID dev_id_ = 0;
bool initialized_ = false;
assets::SoundBank sound_bank_;
assets::MusicArchive music_archive_;
assets::OplTimbreBank opl_bank_;
assets::SoundFontBank sf_bank_;
assets::SoundFontBank custom_sf_bank_;
bool has_custom_sf_ = false;
// Pre-parsed sequences for 2 banks (Adlib .XMI and AWE32 .WTB) x 5 songs
std::array<assets::XmiSequence, 5> opl_seqs_{};
std::array<assets::XmiSequence, 5> wt_seqs_{};
std::array<assets::SoundSample, 5> custom_wav_tracks_{};
Opl3Synth opl_synth_;
SfSynth sf_synth_;
XmidiPlayer xmi_player_;
MusicBackend active_backend_ = MusicBackend::Opl3;
MusicBackend requested_backend_ = MusicBackend::Opl3;
MusicTrackId active_track_ = MusicTrackId::TitleIntro;
bool active_loop_ = true;
double custom_music_pos_ = 0.0;
bool custom_music_playing_ = false;
std::array<SfxVoice, kMaxSfxVoices> sfx_voices_{};
uint64_t mix_sample_clock_ = static_cast<uint64_t>(kSampleRate) * 60ull;
uint64_t voice_seq_ = 0;
std::array<uint64_t, 64> last_play_sample_gameplay_{};
std::array<uint64_t, 64> last_play_sample_intro_{};
const assets::SoundSample* engine_sample_ = nullptr;
const assets::SoundSample* scrape_sample_ = nullptr;
double engine_pos_ = 0.0;
double scrape_pos_ = 0.0;
// Lock-free SPSC command ring buffer (game thread -> audio thread)
std::array<AudioCommand, kCmdQueueSize> cmd_ring_{};
std::atomic<uint32_t> cmd_head_{0};
std::atomic<uint32_t> cmd_tail_{0};
// Atomic mix parameters
std::atomic<float> master_vol_{0.85f};
std::atomic<float> sfx_vol_{0.80f};
std::atomic<float> music_vol_{0.75f};
std::atomic<bool> muted_{false};
std::atomic<bool> engine_active_{false};
std::atomic<float> engine_speed_ratio_{0.0f};
std::atomic<bool> engine_boosting_{false};
std::atomic<float> scrape_amount_{0.0f};
};
} // namespace top_octane::audio
+319
View File
@@ -0,0 +1,319 @@
#include "audio/opl3_synth.hpp"
#include "core/math.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::audio {
namespace {
constexpr double kMultTable[16] = {
0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
8.0, 9.0, 10.0, 10.0, 12.0, 12.0, 15.0, 15.0
};
float rate_to_sec(int rate_4bit, bool is_attack) {
if (rate_4bit <= 0) return 8.0f;
if (rate_4bit >= 15) return 0.002f;
// Exponential OPL rate curve mapping 1..14 cleanly to seconds
float norm = static_cast<float>(15 - rate_4bit);
float base = is_attack ? 0.0025f : 0.008f;
return base * std::pow(1.62f, norm);
}
} // namespace
Opl3Synth::Opl3Synth(const assets::OplTimbreBank* bank, int sample_rate)
: bank_(bank), sample_rate_(std::max(sample_rate, 8000)) {
for (int i = 0; i < kNumChannels; ++i) {
channels_[i] = ChannelState{};
channels_[i].bank = (i == 9) ? 127 : 0;
}
}
void Opl3Synth::set_sample_rate(int sample_rate) {
sample_rate_ = std::max(sample_rate, 8000);
}
void Opl3Synth::setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60,
uint8_t reg80, uint8_t regE0, float base_freq,
float vel_scale, bool is_carrier) {
double mult = kMultTable[reg20 & 0x0Fu];
op.phase = 0.0;
op.phase_inc = (static_cast<double>(base_freq) * mult) / static_cast<double>(sample_rate_);
op.am = (reg20 & 0x80u) != 0;
op.vib = (reg20 & 0x40u) != 0;
op.sustain_hold = (reg20 & 0x20u) != 0;
op.wave = regE0 & 7u;
// Total Level (6-bit, 0 = max, 63 = -47.25 dB)
int tl = reg40 & 0x3Fu;
float tl_gain = std::pow(10.0f, (-0.75f * static_cast<float>(tl)) / 20.0f);
op.total_level = tl_gain * (is_carrier ? vel_scale : 1.0f);
int ar = (reg60 >> 4) & 0x0Fu;
int dr = reg60 & 0x0Fu;
int sl = (reg80 >> 4) & 0x0Fu;
int rr = reg80 & 0x0Fu;
op.attack_rate = 1.0f / rate_to_sec(ar, true);
op.decay_rate = 1.0f / rate_to_sec(dr, false);
op.sustain_level = (sl == 15) ? 0.0f : std::pow(10.0f, (-3.0f * static_cast<float>(sl)) / 20.0f);
op.release_rate = 1.0f / rate_to_sec(rr, false);
op.env = 0.0f;
op.stage = EnvStage::Attack;
}
void Opl3Synth::update_voice_freq(Voice& v) {
float bend = channels_[v.channel].pitch_bend_semitones;
float f = v.base_freq * std::pow(2.0f, bend / 12.0f);
const assets::OplPatch* patch = bank_ ? bank_->find(
v.channel == 9 ? v.key : channels_[v.channel].program,
v.channel == 9 ? 127 : channels_[v.channel].bank) : nullptr;
double m0 = patch ? kMultTable[patch->regs[3] & 0x0Fu] : 1.0;
double m1 = patch ? kMultTable[patch->regs[9] & 0x0Fu] : 1.0;
v.op_mod.phase_inc = (static_cast<double>(f) * m0) / static_cast<double>(sample_rate_);
v.op_car.phase_inc = (static_cast<double>(f) * m1) / static_cast<double>(sample_rate_);
}
void Opl3Synth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
if (ch >= kNumChannels) return;
if (vel == 0) {
note_off(ch, key);
return;
}
// Allocate free or oldest voice
int slot = -1;
uint32_t oldest_age = 0xFFFFFFFFu;
int oldest_idx = 0;
for (int i = 0; i < kNumVoices; ++i) {
if (!voices_[i].active) {
slot = i;
break;
}
if (voices_[i].age < oldest_age) {
oldest_age = voices_[i].age;
oldest_idx = i;
}
}
if (slot < 0) slot = oldest_idx;
Voice& v = voices_[slot];
v = Voice{};
v.active = true;
v.channel = ch;
v.key = key;
v.velocity = vel;
v.age = ++voice_counter_;
bool is_drum = (ch == 9);
uint8_t lookup_patch = is_drum ? key : channels_[ch].program;
uint8_t lookup_bank = is_drum ? 127 : channels_[ch].bank;
const assets::OplPatch* patch = bank_ ? bank_->find(lookup_patch, lookup_bank) : nullptr;
float midi_note = static_cast<float>(key);
if (patch && is_drum && patch->regs[2] > 0) {
midi_note = static_cast<float>(patch->regs[2]);
} else if (patch && !is_drum) {
midi_note += static_cast<float>(static_cast<int8_t>(patch->regs[2]));
}
v.base_freq = 440.0f * std::pow(2.0f, (midi_note - 69.0f) / 12.0f);
float vel_scale = std::clamp(static_cast<float>(vel) / 127.0f, 0.08f, 1.0f);
if (patch) {
uint8_t c0 = patch->regs[8];
int fb = (c0 >> 1) & 7;
v.feedback = (fb == 0) ? 0.0f : (static_cast<float>(1 << fb) / 64.0f);
v.additive = (c0 & 1u) != 0;
setup_operator(v.op_mod, patch->regs[3], patch->regs[4], patch->regs[5],
patch->regs[6], patch->regs[7], v.base_freq,
v.additive ? vel_scale : 1.0f, v.additive);
setup_operator(v.op_car, patch->regs[9], patch->regs[10], patch->regs[11],
patch->regs[12], patch->regs[13], v.base_freq,
vel_scale, true);
} else {
v.feedback = 0.0f;
v.additive = false;
setup_operator(v.op_mod, 0x21, 0x18, 0xF2, 0x45, 0x00, v.base_freq, 1.0f, false);
setup_operator(v.op_car, 0x21, 0x08, 0xF4, 0x36, 0x00, v.base_freq, vel_scale, true);
}
update_voice_freq(v);
}
void Opl3Synth::note_off(uint8_t ch, uint8_t key) {
for (auto& v : voices_) {
if (v.active && v.channel == ch && v.key == key) {
if (v.op_car.stage != EnvStage::Off) v.op_car.stage = EnvStage::Release;
if (v.op_mod.stage != EnvStage::Off) v.op_mod.stage = EnvStage::Release;
}
}
}
void Opl3Synth::program_change(uint8_t ch, uint8_t program) {
if (ch < kNumChannels) channels_[ch].program = program;
}
void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
if (ch >= kNumChannels) return;
switch (cc) {
case 0: // Bank Select MSB
channels_[ch].bank = (ch == 9) ? 127 : val;
break;
case 7: // Volume
channels_[ch].volume = static_cast<float>(val) / 127.0f;
break;
case 10: // Pan
channels_[ch].pan = (static_cast<float>(val) - 64.0f) / 64.0f;
break;
case 11: // Expression
channels_[ch].expression = static_cast<float>(val) / 127.0f;
break;
case 120:
case 123: // All Sound/Notes Off
for (auto& v : voices_) {
if (v.channel == ch) v.active = false;
}
break;
default:
break;
}
}
void Opl3Synth::pitch_bend(uint8_t ch, int16_t bend14) {
if (ch >= kNumChannels) return;
channels_[ch].pitch_bend_semitones = (static_cast<float>(bend14) / 8192.0f) * 2.0f;
for (auto& v : voices_) {
if (v.active && v.channel == ch) update_voice_freq(v);
}
}
void Opl3Synth::all_notes_off() {
for (auto& v : voices_) {
v = Voice{};
}
}
void Opl3Synth::step_envelope(Operator& op, float dt) {
switch (op.stage) {
case EnvStage::Off:
op.env = 0.0f;
break;
case EnvStage::Attack:
op.env += op.attack_rate * dt;
if (op.env >= 1.0f) {
op.env = 1.0f;
op.stage = EnvStage::Decay;
}
break;
case EnvStage::Decay:
op.env -= op.decay_rate * dt;
if (op.env <= op.sustain_level) {
op.env = op.sustain_level;
op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release;
}
break;
case EnvStage::Sustain:
op.env = op.sustain_level;
break;
case EnvStage::Release:
op.env -= op.release_rate * dt;
if (op.env <= 0.0005f) {
op.env = 0.0f;
op.stage = EnvStage::Off;
}
break;
}
}
float Opl3Synth::eval_waveform(uint8_t wave, double phase) {
double p = phase - std::floor(phase);
switch (wave & 7u) {
case 0: // Full sine
return static_cast<float>(std::sin(p * kTwoPi));
case 1: // Half-sine
return p < 0.5 ? static_cast<float>(std::sin(p * kTwoPi)) : 0.0f;
case 2: // Abs-sine
return static_cast<float>(std::abs(std::sin(p * kTwoPi)));
case 3: // Quarter-pulse sine
return (p < 0.25 || (p >= 0.5 && p < 0.75)) ?
static_cast<float>(std::abs(std::sin(p * kTwoPi))) : 0.0f;
case 4: // Alternating double-freq sine
return p < 0.5 ? static_cast<float>(std::sin(p * 2.0 * kTwoPi)) : 0.0f;
case 5: // Alternating double-freq abs-sine
return p < 0.5 ? static_cast<float>(std::abs(std::sin(p * 2.0 * kTwoPi))) : 0.0f;
case 6: // Square
return p < 0.5 ? 1.0f : -1.0f;
case 7: // Derived exponential/saw
return p < 0.5 ? static_cast<float>(1.0 - p * 4.0) : static_cast<float>((p - 0.5) * 4.0 - 1.0);
default:
return 0.0f;
}
}
void Opl3Synth::render(float* stereo_out, int frames) {
const float dt = 1.0f / static_cast<float>(sample_rate_);
const double lfo_inc = 6.0 / static_cast<double>(sample_rate_);
for (int f = 0; f < frames; ++f) {
lfo_phase_ += lfo_inc;
if (lfo_phase_ >= 1.0) lfo_phase_ -= 1.0;
float lfo = static_cast<float>(std::sin(lfo_phase_ * kTwoPi));
float left = 0.0f;
float right = 0.0f;
for (auto& v : voices_) {
if (!v.active) continue;
step_envelope(v.op_mod, dt);
step_envelope(v.op_car, dt);
if (v.op_car.stage == EnvStage::Off && (!v.additive || v.op_mod.stage == EnvStage::Off)) {
v.active = false;
continue;
}
float vib0 = v.op_mod.vib ? (1.0f + 0.008f * lfo) : 1.0f;
float vib1 = v.op_car.vib ? (1.0f + 0.008f * lfo) : 1.0f;
v.op_mod.phase += v.op_mod.phase_inc * vib0;
v.op_mod.phase -= std::floor(v.op_mod.phase);
float fb_mod = 0.5f * (v.prev_mod0 + v.prev_mod1) * v.feedback;
float m_raw = eval_waveform(v.op_mod.wave, v.op_mod.phase + fb_mod);
v.prev_mod1 = v.prev_mod0;
v.prev_mod0 = m_raw;
float am0 = v.op_mod.am ? (1.0f - 0.12f * (0.5f + 0.5f * lfo)) : 1.0f;
float mod_out = m_raw * v.op_mod.env * v.op_mod.total_level * am0;
v.op_car.phase += v.op_car.phase_inc * vib1;
v.op_car.phase -= std::floor(v.op_car.phase);
float am1 = v.op_car.am ? (1.0f - 0.12f * (0.5f + 0.5f * lfo)) : 1.0f;
float sample = 0.0f;
if (v.additive) {
float car_raw = eval_waveform(v.op_car.wave, v.op_car.phase);
sample = (mod_out + car_raw * v.op_car.env * v.op_car.total_level * am1) * 0.5f;
} else {
// FM phase modulation depth
float car_raw = eval_waveform(v.op_car.wave, v.op_car.phase + static_cast<double>(mod_out * 1.15f));
sample = car_raw * v.op_car.env * v.op_car.total_level * am1;
}
const ChannelState& cs = channels_[v.channel];
float ch_gain = cs.volume * cs.expression * 0.55f;
float pan_norm = std::clamp(cs.pan, -1.0f, 1.0f);
float gl = std::sqrt(0.5f * (1.0f - pan_norm));
float gr = std::sqrt(0.5f * (1.0f + pan_norm));
left += sample * ch_gain * gl;
right += sample * ch_gain * gr;
}
stereo_out[f * 2 + 0] += std::tanh(left * 0.9f);
stereo_out[f * 2 + 1] += std::tanh(right * 0.9f);
}
}
} // namespace top_octane::audio
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include "assets/music_bank.hpp"
#include <array>
#include <cstdint>
namespace top_octane::audio {
// Abstract MIDI synthesizer interface used by XmidiPlayer
class IMidiSynth {
public:
virtual ~IMidiSynth() = default;
virtual void set_sample_rate(int sample_rate) = 0;
virtual void note_on(uint8_t ch, uint8_t key, uint8_t vel) = 0;
virtual void note_off(uint8_t ch, uint8_t key) = 0;
virtual void program_change(uint8_t ch, uint8_t program) = 0;
virtual void control_change(uint8_t ch, uint8_t cc, uint8_t val) = 0;
virtual void pitch_bend(uint8_t ch, int16_t bend14) = 0; // -8192..+8191
virtual void all_notes_off() = 0;
virtual void render(float* stereo_out, int frames) = 0;
};
// Self-contained Yamaha OPL3 FM synthesizer driven by Miles SAMPLE.OPL timbres
class Opl3Synth final : public IMidiSynth {
public:
static constexpr int kNumVoices = 18;
static constexpr int kNumChannels = 16;
explicit Opl3Synth(const assets::OplTimbreBank* bank = nullptr, int sample_rate = 48000);
void set_timbre_bank(const assets::OplTimbreBank* bank) { bank_ = bank; }
void set_sample_rate(int sample_rate) override;
void note_on(uint8_t ch, uint8_t key, uint8_t vel) override;
void note_off(uint8_t ch, uint8_t key) override;
void program_change(uint8_t ch, uint8_t program) override;
void control_change(uint8_t ch, uint8_t cc, uint8_t val) override;
void pitch_bend(uint8_t ch, int16_t bend14) override;
void all_notes_off() override;
void render(float* stereo_out, int frames) override;
private:
enum class EnvStage { Off = 0, Attack, Decay, Sustain, Release };
struct Operator {
double phase = 0.0;
double phase_inc = 0.0;
float env = 0.0f; // 0..1 linear amplitude
EnvStage stage = EnvStage::Off;
float attack_rate = 0.0f;
float decay_rate = 0.0f;
float sustain_level = 0.5f;
float release_rate = 0.0f;
float total_level = 1.0f; // linear scale from TL + KSL + vel
uint8_t wave = 0;
bool am = false;
bool vib = false;
bool sustain_hold = true;
};
struct Voice {
bool active = false;
uint8_t channel = 0;
uint8_t key = 0;
uint8_t velocity = 100;
uint32_t age = 0;
float base_freq = 440.0f;
float feedback = 0.0f;
bool additive = false;
float prev_mod0 = 0.0f;
float prev_mod1 = 0.0f;
Operator op_mod{};
Operator op_car{};
};
struct ChannelState {
uint8_t program = 0;
uint8_t bank = 0;
float volume = 1.0f;
float expression = 1.0f;
float pan = 0.0f; // -1..+1
float pitch_bend_semitones = 0.0f;
};
void setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60,
uint8_t reg80, uint8_t regE0, float base_freq, float vel_scale, bool is_carrier);
void step_envelope(Operator& op, float dt);
static float eval_waveform(uint8_t wave, double phase);
void update_voice_freq(Voice& v);
const assets::OplTimbreBank* bank_ = nullptr;
int sample_rate_ = 48000;
uint32_t voice_counter_ = 0;
double lfo_phase_ = 0.0;
std::array<Voice, kNumVoices> voices_{};
std::array<ChannelState, kNumChannels> channels_{};
};
} // namespace top_octane::audio
+254
View File
@@ -0,0 +1,254 @@
#include "audio/sf_synth.hpp"
#include "core/math.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::audio {
SfSynth::SfSynth(const assets::SoundFontBank* sf,
const assets::OplTimbreBank* opl_fallback, int sample_rate)
: sf_(sf), opl_fallback_(opl_fallback, sample_rate),
sample_rate_(std::max(sample_rate, 8000)) {
for (int i = 0; i < 16; ++i) {
channels_[i].bank = (i == 9) ? 128 : 0;
}
}
void SfSynth::set_sample_rate(int sample_rate) {
sample_rate_ = std::max(sample_rate, 8000);
opl_fallback_.set_sample_rate(sample_rate_);
}
SfSynth::RomWaveKind SfSynth::classify_rom_sample(const std::string& name) {
if (name.find("Square") != std::string::npos) return RomWaveKind::Square;
if (name.find("Saw") != std::string::npos) return RomWaveKind::Saw;
if (name.find("Bass") != std::string::npos) return RomWaveKind::SynthBass;
if (name.find("Glass") != std::string::npos || name.find("Xylo") != std::string::npos ||
name.find("Marimba") != std::string::npos) {
return RomWaveKind::Bell;
}
if (name.find("Bongo") != std::string::npos || name.find("Click") != std::string::npos) {
return RomWaveKind::Perc;
}
return RomWaveKind::Sine;
}
void SfSynth::note_on(uint8_t ch, uint8_t key, uint8_t vel) {
if (ch >= 16) return;
if (vel == 0) {
note_off(ch, key);
return;
}
const ChState& cs = channels_[ch];
const assets::SoundFontPreset* preset = sf_ ? sf_->find_preset(cs.bank, cs.program) : nullptr;
if (!preset && sf_ && cs.bank != 0) {
preset = sf_->find_preset(0, cs.program);
}
const assets::SoundFontZone* matched = nullptr;
if (preset) {
for (const auto& z : preset->zones) {
if (key >= z.key_lo && key <= z.key_hi && vel >= z.vel_lo && vel <= z.vel_hi) {
matched = &z;
break;
}
}
}
if (!matched || matched->sample_id < 0 ||
static_cast<size_t>(matched->sample_id) >= sf_->samples.size()) {
// Delegate unmapped GM/drum presets to OPL3 fallback seamlessly
opl_fallback_.note_on(ch, key, vel);
return;
}
const assets::SoundFontSample& smp = sf_->samples[matched->sample_id];
int slot = -1;
uint32_t oldest = 0xFFFFFFFFu;
int oldest_idx = 0;
for (int i = 0; i < kMaxVoices; ++i) {
if (!voices_[i].active) {
slot = i;
break;
}
if (voices_[i].age < oldest) {
oldest = voices_[i].age;
oldest_idx = i;
}
}
if (slot < 0) slot = oldest_idx;
WtVoice& v = voices_[slot];
v = WtVoice{};
v.active = true;
v.channel = ch;
v.key = key;
v.age = ++age_counter_;
v.sample_idx = matched->sample_id;
v.loop = (matched->sample_mode & 1) != 0;
v.env = 1.0f;
int root = (matched->root_key_override >= 0) ? matched->root_key_override : smp.root_key;
float pitch_ratio = std::pow(2.0f, (static_cast<float>(key) - static_cast<float>(root) +
static_cast<float>(smp.fine_tune) / 100.0f) / 12.0f);
if (smp.in_ram) {
v.rom_kind = RomWaveKind::None;
v.pos = static_cast<double>(smp.start);
v.step = (static_cast<double>(smp.sample_rate) / static_cast<double>(sample_rate_)) * pitch_ratio;
} else {
v.rom_kind = classify_rom_sample(smp.name);
double freq = 440.0 * std::pow(2.0, (static_cast<double>(key) - 69.0) / 12.0);
v.step = freq / static_cast<double>(sample_rate_);
v.pos = 0.0;
v.loop = (v.rom_kind != RomWaveKind::Perc && v.rom_kind != RomWaveKind::Bell);
}
float atten = std::pow(10.0f, -matched->attenuation_db / 20.0f);
v.gain = (static_cast<float>(vel) / 127.0f) * atten * 0.95f;
v.pan = std::clamp(cs.pan + static_cast<float>(matched->pan_tenths_pct) / 500.0f, -1.0f, 1.0f);
}
void SfSynth::note_off(uint8_t ch, uint8_t key) {
opl_fallback_.note_off(ch, key);
for (auto& v : voices_) {
if (v.active && v.channel == ch && v.key == key) {
v.releasing = true;
}
}
}
void SfSynth::program_change(uint8_t ch, uint8_t program) {
opl_fallback_.program_change(ch, program);
if (ch < 16) channels_[ch].program = program;
}
void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) {
opl_fallback_.control_change(ch, cc, val);
if (ch >= 16) return;
switch (cc) {
case 0:
channels_[ch].bank = (ch == 9) ? 128 : val;
break;
case 7:
channels_[ch].volume = static_cast<float>(val) / 127.0f;
break;
case 10:
channels_[ch].pan = (static_cast<float>(val) - 64.0f) / 64.0f;
break;
case 11:
channels_[ch].expression = static_cast<float>(val) / 127.0f;
break;
case 120:
case 123:
for (auto& v : voices_) {
if (v.channel == ch) v.active = false;
}
break;
default:
break;
}
}
void SfSynth::pitch_bend(uint8_t ch, int16_t bend14) {
opl_fallback_.pitch_bend(ch, bend14);
if (ch < 16) {
channels_[ch].pitch_bend_semitones = (static_cast<float>(bend14) / 8192.0f) * 2.0f;
}
}
void SfSynth::all_notes_off() {
opl_fallback_.all_notes_off();
for (auto& v : voices_) v = WtVoice{};
}
float SfSynth::sample_voice(WtVoice& v) {
float bend_mul = std::pow(2.0f, channels_[v.channel].pitch_bend_semitones / 12.0f);
if (v.rom_kind != RomWaveKind::None) {
v.pos += v.step * bend_mul;
double ph = v.pos - std::floor(v.pos);
float out = 0.0f;
switch (v.rom_kind) {
case RomWaveKind::Saw:
out = static_cast<float>(2.0 * ph - 1.0);
break;
case RomWaveKind::Square:
out = (ph < 0.5) ? 0.8f : -0.8f;
break;
case RomWaveKind::SynthBass:
out = static_cast<float>(0.65 * std::sin(ph * kTwoPi) + 0.35 * (2.0 * ph - 1.0));
break;
case RomWaveKind::Bell:
out = static_cast<float>(std::sin(ph * kTwoPi + 0.6 * std::sin(ph * 3.5 * kTwoPi)));
v.env *= 0.9994f;
break;
case RomWaveKind::Perc:
out = static_cast<float>(std::sin(ph * kTwoPi));
v.env *= 0.9985f;
break;
default:
out = static_cast<float>(std::sin(ph * kTwoPi));
break;
}
return out * v.env;
}
if (!sf_ || v.sample_idx < 0 || static_cast<size_t>(v.sample_idx) >= sf_->samples.size()) {
v.active = false;
return 0.0f;
}
const assets::SoundFontSample& smp = sf_->samples[v.sample_idx];
uint32_t i0 = static_cast<uint32_t>(v.pos);
if (i0 + 1 >= smp.end || i0 + 1 >= sf_->sample_pool.size()) {
if (v.loop && smp.loop_end > smp.loop_start) {
v.pos = static_cast<double>(smp.loop_start);
i0 = smp.loop_start;
} else {
v.active = false;
return 0.0f;
}
}
float frac = static_cast<float>(v.pos - static_cast<double>(i0));
float s0 = static_cast<float>(sf_->sample_pool[i0]) / 32768.0f;
float s1 = static_cast<float>(sf_->sample_pool[i0 + 1]) / 32768.0f;
float out = (s0 + (s1 - s0) * frac) * v.env;
v.pos += v.step * bend_mul;
if (v.loop && smp.loop_end > smp.loop_start && v.pos >= static_cast<double>(smp.loop_end)) {
v.pos -= static_cast<double>(smp.loop_end - smp.loop_start);
}
return out;
}
void SfSynth::render(float* stereo_out, int frames) {
opl_fallback_.render(stereo_out, frames);
const float rel_decay = 1.0f / (0.12f * static_cast<float>(sample_rate_));
for (int f = 0; f < frames; ++f) {
float l = 0.0f, r = 0.0f;
for (auto& v : voices_) {
if (!v.active) continue;
if (v.releasing) {
v.env -= rel_decay;
if (v.env <= 0.001f) {
v.active = false;
continue;
}
}
float s = sample_voice(v);
if (!v.active) continue;
const ChState& cs = channels_[v.channel];
float g = v.gain * cs.volume * cs.expression;
float gl = std::sqrt(0.5f * (1.0f - v.pan));
float gr = std::sqrt(0.5f * (1.0f + v.pan));
l += s * g * gl;
r += s * g * gr;
}
stereo_out[f * 2 + 0] = std::tanh(stereo_out[f * 2 + 0] + l);
stereo_out[f * 2 + 1] = std::tanh(stereo_out[f * 2 + 1] + r);
}
}
} // namespace top_octane::audio
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "assets/music_bank.hpp"
#include "audio/opl3_synth.hpp"
#include <array>
#include <cstdint>
#include <vector>
namespace top_octane::audio {
// Creative SoundFont 1.0 (BULLFROG.SBK) & 2.0 (.sf2) wavetable synthesizer with OPL3 fallback
class SfSynth final : public IMidiSynth {
public:
static constexpr int kMaxVoices = 32;
SfSynth(const assets::SoundFontBank* sf = nullptr,
const assets::OplTimbreBank* opl_fallback = nullptr,
int sample_rate = 48000);
void set_soundfont(const assets::SoundFontBank* sf) { sf_ = sf; }
void set_opl_fallback(const assets::OplTimbreBank* opl) { opl_fallback_.set_timbre_bank(opl); }
void set_sample_rate(int sample_rate) override;
void note_on(uint8_t ch, uint8_t key, uint8_t vel) override;
void note_off(uint8_t ch, uint8_t key) override;
void program_change(uint8_t ch, uint8_t program) override;
void control_change(uint8_t ch, uint8_t cc, uint8_t val) override;
void pitch_bend(uint8_t ch, int16_t bend14) override;
void all_notes_off() override;
void render(float* stereo_out, int frames) override;
private:
enum class RomWaveKind { None, Saw, Square, Sine, SynthBass, Bell, Perc };
struct WtVoice {
bool active = false;
bool releasing = false;
uint8_t channel = 0;
uint8_t key = 0;
uint32_t age = 0;
int sample_idx = -1;
RomWaveKind rom_kind = RomWaveKind::None;
bool loop = false;
double pos = 0.0;
double step = 1.0;
float gain = 0.0f;
float env = 0.0f;
float pan = 0.0f;
};
struct ChState {
uint8_t program = 0;
uint16_t bank = 0;
float volume = 1.0f;
float expression = 1.0f;
float pan = 0.0f;
float pitch_bend_semitones = 0.0f;
};
static RomWaveKind classify_rom_sample(const std::string& name);
float sample_voice(WtVoice& v);
const assets::SoundFontBank* sf_ = nullptr;
Opl3Synth opl_fallback_;
int sample_rate_ = 48000;
uint32_t age_counter_ = 0;
std::array<WtVoice, kMaxVoices> voices_{};
std::array<ChState, 16> channels_{};
};
} // namespace top_octane::audio
+117
View File
@@ -0,0 +1,117 @@
#include "audio/xmidi_player.hpp"
#include <algorithm>
namespace top_octane::audio {
void XmidiPlayer::set_sample_rate(int sample_rate) {
sample_rate_ = std::max(sample_rate, 8000);
samples_per_tick_ = static_cast<double>(sample_rate_) / 120.0;
}
void XmidiPlayer::set_sequence(const assets::XmiSequence* seq, bool loop) {
seq_ = seq;
loop_ = loop;
playing_ = (seq != nullptr && !seq->events.empty());
event_cursor_ = 0;
current_tick_ = 0;
sample_accum_ = 0.0;
samples_per_tick_ = static_cast<double>(sample_rate_) / 120.0;
for (auto& n : note_offs_) n = PendingNoteOff{};
}
void XmidiPlayer::stop() {
playing_ = false;
seq_ = nullptr;
for (auto& n : note_offs_) n = PendingNoteOff{};
}
void XmidiPlayer::process_tick(IMidiSynth& synth) {
if (!seq_ || !playing_) return;
// Fire due note-offs
for (auto& n : note_offs_) {
if (n.active && current_tick_ >= n.off_tick) {
synth.note_off(n.channel, n.key);
n.active = false;
}
}
// Fire events at or before current_tick_
const auto& evs = seq_->events;
while (event_cursor_ < evs.size() && evs[event_cursor_].tick <= current_tick_) {
const auto& ev = evs[event_cursor_++];
if (ev.status == 0xFFu) {
// Miles XMIDI stays anchored at 120 ticks/sec; tempo meta adjusts subtly if needed
continue;
}
uint8_t hi = ev.status & 0xF0u;
uint8_t ch = ev.status & 0x0Fu;
switch (hi) {
case 0x80u:
synth.note_off(ch, ev.data1);
break;
case 0x90u:
if (ev.data2 == 0) {
synth.note_off(ch, ev.data1);
} else {
synth.note_on(ch, ev.data1, ev.data2);
if (ev.duration_ticks > 0) {
for (auto& n : note_offs_) {
if (!n.active) {
n.active = true;
n.off_tick = current_tick_ + ev.duration_ticks;
n.channel = ch;
n.key = ev.data1;
break;
}
}
}
}
break;
case 0xB0u:
synth.control_change(ch, ev.data1, ev.data2);
break;
case 0xC0u:
synth.program_change(ch, ev.data1);
break;
case 0xE0u: {
int16_t bend14 = static_cast<int16_t>(((ev.data2 & 0x7Fu) << 7) | (ev.data1 & 0x7Fu)) - 8192;
synth.pitch_bend(ch, bend14);
break;
}
default:
break;
}
}
++current_tick_;
if (event_cursor_ >= evs.size() && current_tick_ > seq_->total_ticks) {
if (loop_) {
synth.all_notes_off();
event_cursor_ = 0;
current_tick_ = 0;
for (auto& n : note_offs_) n = PendingNoteOff{};
} else {
playing_ = false;
}
}
}
void XmidiPlayer::render(float* stereo_out, int frames, IMidiSynth& synth) {
if (!playing_ || !seq_) return;
int offset = 0;
while (offset < frames && playing_) {
if (sample_accum_ <= 0.0) {
process_tick(synth);
sample_accum_ += samples_per_tick_;
}
int step = std::min(frames - offset, std::max(1, static_cast<int>(sample_accum_)));
synth.render(stereo_out + offset * 2, step);
sample_accum_ -= static_cast<double>(step);
offset += step;
}
}
} // namespace top_octane::audio
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include "assets/music_bank.hpp"
#include "audio/opl3_synth.hpp"
#include <array>
#include <cstdint>
namespace top_octane::audio {
// Sample-accurate 120 Hz Miles XMIDI sequencer with fixed-size active note-off table
class XmidiPlayer {
public:
static constexpr int kMaxActiveNotes = 128;
void set_sample_rate(int sample_rate);
void set_sequence(const assets::XmiSequence* seq, bool loop = true);
void stop();
bool is_playing() const { return seq_ != nullptr && playing_; }
// Advances sequencer and synthesizes `frames` stereo samples into `stereo_out` (adds/writes)
void render(float* stereo_out, int frames, IMidiSynth& synth);
private:
struct PendingNoteOff {
bool active = false;
uint32_t off_tick = 0;
uint8_t channel = 0;
uint8_t key = 0;
};
void process_tick(IMidiSynth& synth);
const assets::XmiSequence* seq_ = nullptr;
bool loop_ = true;
bool playing_ = false;
int sample_rate_ = 48000;
size_t event_cursor_ = 0;
uint32_t current_tick_ = 0;
double samples_per_tick_ = 400.0; // 48000 / 120 Hz default
double sample_accum_ = 0.0;
std::array<PendingNoteOff, kMaxActiveNotes> note_offs_{};
};
} // namespace top_octane::audio
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <algorithm>
#include <cstdint>
namespace top_octane {
class FixedStepClock {
public:
static constexpr double kFixedDt = 1.0 / 60.0;
static constexpr double kMaxFrameDt = 0.1;
void reset(uint64_t now_counter, uint64_t freq) {
last_counter_ = now_counter;
freq_ = freq ? freq : 1;
accumulator_ = 0.0;
}
// Returns number of fixed simulation steps to execute this frame
int advance(uint64_t now_counter) {
double dt = static_cast<double>(now_counter - last_counter_) / static_cast<double>(freq_);
last_counter_ = now_counter;
dt = std::clamp(dt, 0.0, kMaxFrameDt);
accumulator_ += dt;
int steps = 0;
while (accumulator_ >= kFixedDt) {
accumulator_ -= kFixedDt;
++steps;
}
return steps;
}
double alpha() const { return accumulator_ / kFixedDt; }
static constexpr double fixed_dt() { return kFixedDt; }
private:
uint64_t last_counter_ = 0;
uint64_t freq_ = 1;
double accumulator_ = 0.0;
};
} // namespace top_octane
+198
View File
@@ -0,0 +1,198 @@
#include "core/config.hpp"
#include <algorithm>
#include <cctype>
#include <fstream>
#include <sstream>
#include <unordered_map>
namespace top_octane {
namespace {
std::string trim(const std::string& s) {
size_t a = 0;
while (a < s.size() && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
size_t b = s.size();
while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
return s.substr(a, b - a);
}
int parse_int(const std::string& v, int def) {
try {
return std::stoi(v);
} catch (...) {
return def;
}
}
float parse_float(const std::string& v, float def) {
try {
return std::stof(v);
} catch (...) {
return def;
}
}
bool parse_bool(const std::string& v, bool def) {
std::string l = v;
for (char& c : l) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (l == "1" || l == "true" || l == "yes" || l == "on") return true;
if (l == "0" || l == "false" || l == "no" || l == "off") return false;
return def;
}
} // namespace
bool GameConfig::load(const std::filesystem::path& path) {
std::ifstream ifs(path);
if (!ifs) return false;
std::unordered_map<std::string, std::string> kv;
std::string section;
std::string line;
while (std::getline(ifs, line)) {
std::string t = trim(line);
if (t.empty() || t[0] == '#' || t[0] == ';') continue;
if (t.front() == '[' && t.back() == ']') {
section = trim(t.substr(1, t.size() - 2));
continue;
}
auto eq = t.find('=');
if (eq == std::string::npos) continue;
std::string k = trim(t.substr(0, eq));
std::string v = trim(t.substr(eq + 1));
kv[section.empty() ? k : (section + "." + k)] = v;
}
auto get = [&](const char* key) -> const std::string* {
auto it = kv.find(key);
return it == kv.end() ? nullptr : &it->second;
};
if (auto* v = get("video.window_width")) window_width = std::clamp(parse_int(*v, window_width), 320, 7680);
if (auto* v = get("video.window_height")) window_height = std::clamp(parse_int(*v, window_height), 200, 4320);
if (auto* v = get("video.fullscreen")) fullscreen = parse_bool(*v, fullscreen);
if (auto* v = get("video.vsync")) vsync = parse_bool(*v, vsync);
if (auto* v = get("video.msaa_samples")) msaa_samples = std::clamp(parse_int(*v, msaa_samples), 0, 16);
if (auto* v = get("video.classic_mode")) classic_mode = parse_bool(*v, classic_mode);
if (auto* v = get("video.classic_hires")) classic_hires = parse_bool(*v, classic_hires);
if (auto* v = get("video.classic_scanlines")) classic_scanlines = parse_bool(*v, classic_scanlines);
if (auto* v = get("video.draw_distance")) draw_distance = std::clamp(parse_float(*v, draw_distance), 20.0f, 200.0f);
if (auto* v = get("video.texture_filter")) texture_filter = static_cast<TextureFilterMode>(std::clamp(parse_int(*v, 1), 0, 1));
if (auto* v = get("video.fov_deg")) fov_deg = std::clamp(parse_float(*v, fov_deg), 45.0f, 110.0f);
if (auto* v = get("audio.music_backend")) music_backend = static_cast<MusicBackend>(std::clamp(parse_int(*v, 0), 0, 2));
if (auto* v = get("audio.master_volume")) master_volume = std::clamp(parse_float(*v, master_volume), 0.0f, 1.0f);
if (auto* v = get("audio.sfx_volume")) sfx_volume = std::clamp(parse_float(*v, sfx_volume), 0.0f, 1.0f);
if (auto* v = get("audio.music_volume")) music_volume = std::clamp(parse_float(*v, music_volume), 0.0f, 1.0f);
if (auto* v = get("audio.mute_on_focus_loss")) mute_on_focus_loss = parse_bool(*v, mute_on_focus_loss);
if (auto* v = get("audio.custom_soundfont_path")) custom_soundfont_path = *v;
if (auto* v = get("controls.gamepad_deadzone")) gamepad_deadzone = std::clamp(parse_float(*v, gamepad_deadzone), 0.0f, 0.5f);
if (auto* v = get("controls.steering_sensitivity")) steering_sensitivity = std::clamp(parse_float(*v, steering_sensitivity), 0.25f, 3.0f);
if (auto* v = get("controls.steering_curve")) steering_curve = std::clamp(parse_float(*v, steering_curve), 0.5f, 3.0f);
if (auto* v = get("controls.rumble_enabled")) rumble_enabled = parse_bool(*v, rumble_enabled);
if (auto* v = get("controls.mouse_steering")) mouse_steering = parse_bool(*v, mouse_steering);
if (auto* v = get("controls.p1_gamepad_index")) p1_gamepad_index = parse_int(*v, p1_gamepad_index);
if (auto* v = get("controls.p2_gamepad_index")) p2_gamepad_index = parse_int(*v, p2_gamepad_index);
if (auto* v = get("keys.steer_left")) keys.steer_left = parse_int(*v, keys.steer_left);
if (auto* v = get("keys.steer_right")) keys.steer_right = parse_int(*v, keys.steer_right);
if (auto* v = get("keys.accelerate")) keys.accelerate = parse_int(*v, keys.accelerate);
if (auto* v = get("keys.brake")) keys.brake = parse_int(*v, keys.brake);
if (auto* v = get("keys.boost")) keys.boost = parse_int(*v, keys.boost);
if (auto* v = get("keys.fire_minigun")) keys.fire_minigun = parse_int(*v, keys.fire_minigun);
if (auto* v = get("keys.fire_missile")) keys.fire_missile = parse_int(*v, keys.fire_missile);
if (auto* v = get("keys.autopilot")) keys.autopilot = parse_int(*v, keys.autopilot);
if (auto* v = get("keys.camera_view")) keys.camera_view = parse_int(*v, keys.camera_view);
if (auto* v = get("keys.hud_toggle")) keys.hud_toggle = parse_int(*v, keys.hud_toggle);
if (auto* v = get("keys.p2_steer_left")) keys.p2_steer_left = parse_int(*v, keys.p2_steer_left);
if (auto* v = get("keys.p2_steer_right")) keys.p2_steer_right = parse_int(*v, keys.p2_steer_right);
if (auto* v = get("keys.p2_accelerate")) keys.p2_accelerate = parse_int(*v, keys.p2_accelerate);
if (auto* v = get("keys.p2_brake")) keys.p2_brake = parse_int(*v, keys.p2_brake);
if (auto* v = get("keys.p2_boost")) keys.p2_boost = parse_int(*v, keys.p2_boost);
if (auto* v = get("keys.p2_fire_minigun")) keys.p2_fire_minigun = parse_int(*v, keys.p2_fire_minigun);
if (auto* v = get("keys.p2_fire_missile")) keys.p2_fire_missile = parse_int(*v, keys.p2_fire_missile);
if (auto* v = get("game.player_name")) player_name = v->substr(0, 12);
if (auto* v = get("game.language")) language = static_cast<Language>(std::clamp(parse_int(*v, 0), 0, 3));
if (auto* v = get("game.preferred_vehicle")) preferred_vehicle = std::clamp(parse_int(*v, 0), 0, 5);
if (auto* v = get("game.preferred_team")) preferred_team = std::clamp(parse_int(*v, 7), 0, 7);
if (auto* v = get("game.default_laps")) default_laps = std::clamp(parse_int(*v, 3), 1, 20);
if (auto* v = get("game.difficulty")) difficulty = std::clamp(parse_int(*v, 1), 0, 2);
if (auto* v = get("game.skip_intro")) skip_intro = parse_bool(*v, skip_intro);
return true;
}
bool GameConfig::save(const std::filesystem::path& path) const {
std::error_code ec;
if (path.has_parent_path()) {
std::filesystem::create_directories(path.parent_path(), ec);
}
std::ofstream ofs(path, std::ios::trunc);
if (!ofs) return false;
ofs << "[video]\n"
<< "window_width=" << window_width << "\n"
<< "window_height=" << window_height << "\n"
<< "fullscreen=" << (fullscreen ? 1 : 0) << "\n"
<< "vsync=" << (vsync ? 1 : 0) << "\n"
<< "msaa_samples=" << msaa_samples << "\n"
<< "classic_mode=" << (classic_mode ? 1 : 0) << "\n"
<< "classic_hires=" << (classic_hires ? 1 : 0) << "\n"
<< "classic_scanlines=" << (classic_scanlines ? 1 : 0) << "\n"
<< "draw_distance=" << draw_distance << "\n"
<< "texture_filter=" << static_cast<int>(texture_filter) << "\n"
<< "fov_deg=" << fov_deg << "\n\n"
<< "[audio]\n"
<< "music_backend=" << static_cast<int>(music_backend) << "\n"
<< "master_volume=" << master_volume << "\n"
<< "sfx_volume=" << sfx_volume << "\n"
<< "music_volume=" << music_volume << "\n"
<< "mute_on_focus_loss=" << (mute_on_focus_loss ? 1 : 0) << "\n"
<< "custom_soundfont_path=" << custom_soundfont_path << "\n\n"
<< "[controls]\n"
<< "gamepad_deadzone=" << gamepad_deadzone << "\n"
<< "steering_sensitivity=" << steering_sensitivity << "\n"
<< "steering_curve=" << steering_curve << "\n"
<< "rumble_enabled=" << (rumble_enabled ? 1 : 0) << "\n"
<< "mouse_steering=" << (mouse_steering ? 1 : 0) << "\n"
<< "p1_gamepad_index=" << p1_gamepad_index << "\n"
<< "p2_gamepad_index=" << p2_gamepad_index << "\n\n"
<< "[keys]\n"
<< "steer_left=" << keys.steer_left << "\n"
<< "steer_right=" << keys.steer_right << "\n"
<< "accelerate=" << keys.accelerate << "\n"
<< "brake=" << keys.brake << "\n"
<< "boost=" << keys.boost << "\n"
<< "fire_minigun=" << keys.fire_minigun << "\n"
<< "fire_missile=" << keys.fire_missile << "\n"
<< "autopilot=" << keys.autopilot << "\n"
<< "camera_view=" << keys.camera_view << "\n"
<< "hud_toggle=" << keys.hud_toggle << "\n"
<< "p2_steer_left=" << keys.p2_steer_left << "\n"
<< "p2_steer_right=" << keys.p2_steer_right << "\n"
<< "p2_accelerate=" << keys.p2_accelerate << "\n"
<< "p2_brake=" << keys.p2_brake << "\n"
<< "p2_boost=" << keys.p2_boost << "\n"
<< "p2_fire_minigun=" << keys.p2_fire_minigun << "\n"
<< "p2_fire_missile=" << keys.p2_fire_missile << "\n\n"
<< "[game]\n"
<< "player_name=" << player_name << "\n"
<< "language=" << static_cast<int>(language) << "\n"
<< "preferred_vehicle=" << preferred_vehicle << "\n"
<< "preferred_team=" << preferred_team << "\n"
<< "default_laps=" << default_laps << "\n"
<< "difficulty=" << difficulty << "\n"
<< "skip_intro=" << (skip_intro ? 1 : 0) << "\n";
return ofs.good();
}
} // namespace top_octane
+95
View File
@@ -0,0 +1,95 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
namespace top_octane {
enum class MusicBackend {
Opl3 = 0,
SoundFont = 1,
Custom = 2,
};
enum class Language {
English = 0,
German = 1,
Spanish = 2,
French = 3,
};
enum class TextureFilterMode {
Nearest = 0,
Linear = 1,
};
struct KeyBindings {
// SDL_Scancode integers for layout-independent bindings
int steer_left = 4; // SDL_SCANCODE_A
int steer_right = 7; // SDL_SCANCODE_D
int accelerate = 26; // SDL_SCANCODE_W
int brake = 22; // SDL_SCANCODE_S
int boost = 225; // SDL_SCANCODE_LSHIFT
int fire_minigun = 44; // SDL_SCANCODE_SPACE
int fire_missile = 8; // SDL_SCANCODE_E
int autopilot = 20; // SDL_SCANCODE_Q
int camera_view = 6; // SDL_SCANCODE_C
int hud_toggle = 11; // SDL_SCANCODE_H
// Player 2 default split-screen keys (Arrows + RCtrl/RShift/Enter)
int p2_steer_left = 80; // SDL_SCANCODE_LEFT
int p2_steer_right = 79; // SDL_SCANCODE_RIGHT
int p2_accelerate = 82; // SDL_SCANCODE_UP
int p2_brake = 81; // SDL_SCANCODE_DOWN
int p2_boost = 229; // SDL_SCANCODE_RSHIFT
int p2_fire_minigun = 228; // SDL_SCANCODE_RCTRL
int p2_fire_missile = 40; // SDL_SCANCODE_RETURN
};
struct GameConfig {
// Video
int window_width = 1280;
int window_height = 720;
bool fullscreen = false;
bool vsync = true;
int msaa_samples = 4;
bool classic_mode = false;
bool classic_hires = true; // false: 320x200, true: 640x480
bool classic_scanlines = false;
float draw_distance = 75.0f; // tiles
TextureFilterMode texture_filter = TextureFilterMode::Linear;
float fov_deg = 70.0f;
// Audio
MusicBackend music_backend = MusicBackend::Opl3;
float master_volume = 0.85f;
float sfx_volume = 0.80f;
float music_volume = 0.75f;
bool mute_on_focus_loss = true;
std::string custom_soundfont_path;
// Controls
float gamepad_deadzone = 0.14f;
float steering_sensitivity = 1.0f;
float steering_curve = 1.35f;
bool rumble_enabled = true;
bool mouse_steering = false;
int p1_gamepad_index = 0; // -1 = keyboard only, 0+ = auto/gamepad
int p2_gamepad_index = 1;
KeyBindings keys{};
// Game
std::string player_name = "PLAYER";
Language language = Language::English;
int preferred_vehicle = 0;
int preferred_team = 7; // Bullfrog
int default_laps = 3;
int difficulty = 1; // 0=Easy, 1=Medium, 2=Hard
bool skip_intro = false;
bool load(const std::filesystem::path& path);
bool save(const std::filesystem::path& path) const;
};
} // namespace top_octane
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <cstdio>
#include <cstdarg>
namespace top_octane::log {
enum class Level {
Debug = 0,
Info,
Warn,
Error
};
inline Level& min_level() {
static Level lvl = Level::Info;
return lvl;
}
inline void write(Level lvl, const char* tag, const char* fmt, ...) {
if (static_cast<int>(lvl) < static_cast<int>(min_level())) {
return;
}
std::FILE* out = (lvl >= Level::Warn) ? stderr : stdout;
std::fprintf(out, "[%s] ", tag);
va_list args;
va_start(args, fmt);
std::vfprintf(out, fmt, args);
va_end(args);
std::fputc('\n', out);
}
} // namespace top_octane::log
#define LOG_DEBUG(...) ::top_octane::log::write(::top_octane::log::Level::Debug, "DBG", __VA_ARGS__)
#define LOG_INFO(...) ::top_octane::log::write(::top_octane::log::Level::Info, "INF", __VA_ARGS__)
#define LOG_WARN(...) ::top_octane::log::write(::top_octane::log::Level::Warn, "WRN", __VA_ARGS__)
#define LOG_ERROR(...) ::top_octane::log::write(::top_octane::log::Level::Error, "ERR", __VA_ARGS__)
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <algorithm>
#include <cmath>
#include <cstdint>
namespace top_octane {
constexpr float kPi = 3.14159265358979323846f;
constexpr float kTwoPi = 6.28318530717958647692f;
constexpr float kHalfPi = 1.57079632679489661923f;
inline float deg_to_rad(float deg) { return deg * (kPi / 180.0f); }
inline float rad_to_deg(float rad) { return rad * (180.0f / kPi); }
inline float wrap_angle(float a) {
while (a > kPi) a -= kTwoPi;
while (a < -kPi) a += kTwoPi;
return a;
}
inline float lerp(float a, float b, float t) { return a + (b - a) * t; }
inline float lerp_angle(float a, float b, float t) {
return wrap_angle(a + wrap_angle(b - a) * t);
}
struct Vec2 {
float x = 0.0f, y = 0.0f;
Vec2() = default;
Vec2(float x_, float y_) : x(x_), y(y_) {}
Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; }
Vec2 operator-(const Vec2& o) const { return {x - o.x, y - o.y}; }
Vec2 operator*(float s) const { return {x * s, y * s}; }
float dot(const Vec2& o) const { return x * o.x + y * o.y; }
float len_sq() const { return x * x + y * y; }
float len() const { return std::sqrt(len_sq()); }
Vec2 normalized() const {
float l = len();
return l > 1e-6f ? Vec2{x / l, y / l} : Vec2{0.0f, 0.0f};
}
};
struct Vec3 {
float x = 0.0f, y = 0.0f, z = 0.0f;
Vec3() = default;
Vec3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {}
Vec3 operator+(const Vec3& o) const { return {x + o.x, y + o.y, z + o.z}; }
Vec3 operator-(const Vec3& o) const { return {x - o.x, y - o.y, z - o.z}; }
Vec3 operator-() const { return {-x, -y, -z}; }
Vec3 operator*(float s) const { return {x * s, y * s, z * s}; }
Vec3 operator/(float s) const { return {x / s, y / s, z / s}; }
Vec3& operator+=(const Vec3& o) { x += o.x; y += o.y; z += o.z; return *this; }
Vec3& operator-=(const Vec3& o) { x -= o.x; y -= o.y; z -= o.z; return *this; }
Vec3& operator*=(float s) { x *= s; y *= s; z *= s; return *this; }
float dot(const Vec3& o) const { return x * o.x + y * o.y + z * o.z; }
Vec3 cross(const Vec3& o) const {
return {y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x};
}
float len_sq() const { return x * x + y * y + z * z; }
float len() const { return std::sqrt(len_sq()); }
Vec3 normalized() const {
float l = len();
return l > 1e-6f ? Vec3{x / l, y / l, z / l} : Vec3{0.0f, 0.0f, 0.0f};
}
};
inline Vec3 lerp(const Vec3& a, const Vec3& b, float t) {
return {lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t)};
}
struct Vec4 {
float x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f;
Vec4() = default;
Vec4(float x_, float y_, float z_, float w_) : x(x_), y(y_), z(z_), w(w_) {}
};
// Column-major 4x4 matrix matching OpenGL conventions
struct Mat4 {
float m[16]{};
static Mat4 identity() {
Mat4 r;
r.m[0] = r.m[5] = r.m[10] = r.m[15] = 1.0f;
return r;
}
static Mat4 translate(const Vec3& t) {
Mat4 r = identity();
r.m[12] = t.x;
r.m[13] = t.y;
r.m[14] = t.z;
return r;
}
static Mat4 scale(const Vec3& s) {
Mat4 r;
r.m[0] = s.x;
r.m[5] = s.y;
r.m[10] = s.z;
r.m[15] = 1.0f;
return r;
}
static Mat4 rotate_x(float rad) {
Mat4 r = identity();
float c = std::cos(rad), s = std::sin(rad);
r.m[5] = c; r.m[9] = -s;
r.m[6] = s; r.m[10] = c;
return r;
}
static Mat4 rotate_y(float rad) {
Mat4 r = identity();
float c = std::cos(rad), s = std::sin(rad);
r.m[0] = c; r.m[8] = s;
r.m[2] = -s; r.m[10] = c;
return r;
}
static Mat4 rotate_z(float rad) {
Mat4 r = identity();
float c = std::cos(rad), s = std::sin(rad);
r.m[0] = c; r.m[4] = -s;
r.m[1] = s; r.m[5] = c;
return r;
}
static Mat4 perspective(float fovy_rad, float aspect, float znear, float zfar) {
Mat4 r;
float f = 1.0f / std::tan(fovy_rad * 0.5f);
r.m[0] = f / std::max(aspect, 0.001f);
r.m[5] = f;
r.m[10] = (zfar + znear) / (znear - zfar);
r.m[11] = -1.0f;
r.m[14] = (2.0f * zfar * znear) / (znear - zfar);
return r;
}
static Mat4 ortho(float left, float right, float bottom, float top, float znear = -1.0f, float zfar = 1.0f) {
Mat4 r = identity();
r.m[0] = 2.0f / (right - left);
r.m[5] = 2.0f / (top - bottom);
r.m[10] = -2.0f / (zfar - znear);
r.m[12] = -(right + left) / (right - left);
r.m[13] = -(top + bottom) / (top - bottom);
r.m[14] = -(zfar + znear) / (zfar - znear);
return r;
}
static Mat4 look_at(const Vec3& eye, const Vec3& center, const Vec3& up) {
Vec3 f = (center - eye).normalized();
Vec3 s = f.cross(up).normalized();
Vec3 u = s.cross(f);
Mat4 r = identity();
r.m[0] = s.x; r.m[4] = s.y; r.m[8] = s.z;
r.m[1] = u.x; r.m[5] = u.y; r.m[9] = u.z;
r.m[2] = -f.x; r.m[6] = -f.y; r.m[10] = -f.z;
r.m[12] = -s.dot(eye);
r.m[13] = -u.dot(eye);
r.m[14] = f.dot(eye);
return r;
}
Mat4 operator*(const Mat4& o) const {
Mat4 r;
for (int col = 0; col < 4; ++col) {
for (int row = 0; row < 4; ++row) {
float sum = 0.0f;
for (int k = 0; k < 4; ++k) {
sum += m[k * 4 + row] * o.m[col * 4 + k];
}
r.m[col * 4 + row] = sum;
}
}
return r;
}
};
} // namespace top_octane
+190
View File
@@ -0,0 +1,190 @@
#include "core/vfs.hpp"
#include "core/log.hpp"
#include <SDL.h>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <sstream>
namespace top_octane {
namespace {
std::string to_lower_ascii(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
std::vector<std::string> split_rel_path(const std::string& rel) {
std::vector<std::string> parts;
std::string cur;
for (char c : rel) {
if (c == '/' || c == '\\') {
if (!cur.empty()) {
parts.push_back(cur);
cur.clear();
}
} else {
cur.push_back(c);
}
}
if (!cur.empty()) {
parts.push_back(cur);
}
return parts;
}
bool is_valid_hioctane_dir(const std::filesystem::path& p) {
std::error_code ec;
if (!std::filesystem::is_directory(p, ec)) {
return false;
}
// Check case-insensitively for both DATA and MAPS subdirectories
bool has_data = false;
bool has_maps = false;
for (const auto& ent : std::filesystem::directory_iterator(p, ec)) {
if (ent.is_directory(ec)) {
std::string name = to_lower_ascii(ent.path().filename().string());
if (name == "data") has_data = true;
else if (name == "maps") has_maps = true;
}
}
return has_data && has_maps;
}
} // namespace
bool Vfs::init(const std::string& explicit_data_dir) {
std::vector<std::filesystem::path> candidates;
if (!explicit_data_dir.empty()) {
candidates.emplace_back(explicit_data_dir);
}
if (const char* env_dir = std::getenv("HIOCTANE_DATA")) {
if (*env_dir) {
candidates.emplace_back(env_dir);
}
}
std::error_code ec;
std::filesystem::path cwd = std::filesystem::current_path(ec);
std::filesystem::path base_dir;
if (char* base_p = SDL_GetBasePath()) {
base_dir = std::filesystem::path(base_p);
SDL_free(base_p);
}
auto add_folder_candidates = [&](const char* folder_name) {
if (!cwd.empty()) {
candidates.emplace_back(cwd / folder_name);
candidates.emplace_back(cwd.parent_path() / folder_name);
}
if (!base_dir.empty()) {
candidates.emplace_back(base_dir / folder_name);
candidates.emplace_back(base_dir.parent_path() / folder_name);
}
};
add_folder_candidates("data");
add_folder_candidates("HiOctane");
data_root_.clear();
for (const auto& c : candidates) {
if (is_valid_hioctane_dir(c)) {
data_root_ = std::filesystem::weakly_canonical(c, ec);
if (ec) data_root_ = c;
break;
}
}
if (char* pref = SDL_GetPrefPath("top-octane", "TopOctane")) {
pref_dir_ = pref;
SDL_free(pref);
} else {
pref_dir_ = std::filesystem::current_path() / "save";
}
std::filesystem::create_directories(pref_dir_, ec);
if (data_root_.empty()) {
LOG_ERROR("Could not locate Top-Octane asset directory (expected ./data or --data-dir)");
return false;
}
LOG_INFO("Using read-only asset directory: %s", data_root_.string().c_str());
LOG_INFO("Using user save/config directory: %s", pref_dir_.string().c_str());
return true;
}
bool Vfs::resolve(const std::string& rel_path, std::filesystem::path& out_path) const {
if (data_root_.empty()) return false;
std::filesystem::path cur = data_root_;
std::error_code ec;
for (const std::string& part : split_rel_path(rel_path)) {
std::filesystem::path direct = cur / part;
if (std::filesystem::exists(direct, ec)) {
cur = direct;
continue;
}
std::string target = to_lower_ascii(part);
bool matched = false;
if (std::filesystem::is_directory(cur, ec)) {
for (const auto& ent : std::filesystem::directory_iterator(cur, ec)) {
if (to_lower_ascii(ent.path().filename().string()) == target) {
cur = ent.path();
matched = true;
break;
}
}
}
if (!matched) {
return false;
}
}
out_path = cur;
return std::filesystem::is_regular_file(out_path, ec);
}
bool Vfs::exists(const std::string& rel_path) const {
std::filesystem::path p;
return resolve(rel_path, p);
}
bool Vfs::read_file(const std::string& rel_path, std::vector<uint8_t>& out_data) const {
std::filesystem::path p;
if (!resolve(rel_path, p)) {
return false;
}
return read_raw_file(p, out_data);
}
bool Vfs::read_raw_file(const std::filesystem::path& path, std::vector<uint8_t>& out_data) {
std::ifstream ifs(path, std::ios::binary | std::ios::ate);
if (!ifs) return false;
const auto sz = ifs.tellg();
if (sz < 0) return false;
out_data.resize(static_cast<size_t>(sz));
ifs.seekg(0, std::ios::beg);
if (sz > 0 && !ifs.read(reinterpret_cast<char*>(out_data.data()), sz)) {
out_data.clear();
return false;
}
return true;
}
bool Vfs::write_raw_file(const std::filesystem::path& path, const void* data, size_t size) {
std::error_code ec;
if (path.has_parent_path()) {
std::filesystem::create_directories(path.parent_path(), ec);
}
std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
if (!ofs) return false;
if (size > 0 && !ofs.write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size))) {
return false;
}
return ofs.good();
}
} // namespace top_octane
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace top_octane {
class Vfs {
public:
// Initializes read-only asset lookup from explicit path, HIOCTANE_DATA env, ./data (default), or ./HiOctane fallback
bool init(const std::string& explicit_data_dir = "");
const std::filesystem::path& data_root() const { return data_root_; }
const std::filesystem::path& pref_dir() const { return pref_dir_; }
// Case-insensitive lookup inside data_root (relative paths use '/' or '\\')
bool resolve(const std::string& rel_path, std::filesystem::path& out_path) const;
bool exists(const std::string& rel_path) const;
bool read_file(const std::string& rel_path, std::vector<uint8_t>& out_data) const;
// Static binary helper for reading arbitrary paths
static bool read_raw_file(const std::filesystem::path& path, std::vector<uint8_t>& out_data);
static bool write_raw_file(const std::filesystem::path& path, const void* data, size_t size);
private:
std::filesystem::path data_root_;
std::filesystem::path pref_dir_;
};
} // namespace top_octane
File diff suppressed because it is too large. Load diff
+140
View File
@@ -0,0 +1,140 @@
#pragma once
#include "assets/flic.hpp"
#include "assets/level.hpp"
#include "assets/palette.hpp"
#include "audio/audio_engine.hpp"
#include "core/clock.hpp"
#include "core/config.hpp"
#include "core/vfs.hpp"
#include "game/game_modes.hpp"
#include "input/input_manager.hpp"
#include "render/ui_renderer.hpp"
#include "render/world_renderer.hpp"
#include "sim/race_sim.hpp"
#include <SDL.h>
#include <string>
#include <vector>
namespace top_octane::game {
struct LaunchOptions {
std::string data_dir;
int start_track = 0; // 1..6 to jump straight into race
bool track_viewer = false;
bool force_classic = false;
bool force_fullscreen = false;
int force_backend = -1; // 0=opl3, 1=sf, 2=custom
bool skip_intro = false;
int smoke_test_frames = 0; // >0: run N real frames and exit cleanly
};
class GameApp {
public:
bool init(const LaunchOptions& opts);
int run();
void shutdown();
private:
enum class ScreenState {
Intro = 0,
Title,
MainMenu,
ChampionshipMenu,
TrackSelect,
VehicleSelect,
Highscores,
Options,
TrackViewer,
Racing,
Paused,
PostRace,
};
enum class OptionsTab {
Video = 0,
Audio,
Controls,
Game,
};
void enter_state(ScreenState s);
void start_race_session();
void enter_track_viewer(int track_num);
void preload_world_models(int track_num);
void update_menu(float dt);
void update_track_viewer(float dt);
void update_racing_step(float dt);
void render_frame(float alpha);
void render_hud_viewport(const sim::CraftState& craft, const render::RenderCamera& cam,
int vx, int vy, int vw, int vh, bool show_minimap);
void render_minimap(const sim::CraftState& focus, float mx, float my, float size);
void render_menus();
void handle_sim_events();
void apply_video_settings();
void toggle_fullscreen();
void save_all_user_data();
Vfs vfs_;
GameConfig cfg_;
LaunchOptions opts_;
SDL_Window* window_ = nullptr;
SDL_GLContext gl_ctx_ = nullptr;
int win_w_ = 1280;
int win_h_ = 720;
bool running_ = false;
bool window_focused_ = true;
assets::Palette palette_;
assets::FlicPlayer flic_;
render::WorldRenderer world_ren_;
render::UiRenderer ui_ren_;
InputManager input_;
audio::AudioEngine audio_;
FixedStepClock clock_;
ScreenState state_ = ScreenState::Intro;
OptionsTab opt_tab_ = OptionsTab::Video;
int menu_cursor_ = 0;
int rebind_slot_ = -1;
int cam_mode_ = 0; // 0=chase, 1=close chase, 2=cockpit/hood
// Race / Mode selection state
sim::GameMode selected_mode_ = sim::GameMode::SingleRace;
int selected_track_ = 1;
int selected_laps_ = 3;
int selected_difficulty_ = 1;
int selected_opponents_ = 7;
int p1_veh_ = 0, p1_team_ = 7;
int p2_veh_ = 3, p2_team_ = 1;
int champ_slot_cursor_ = 0;
int post_race_page_ = 0;
int post_race_record_flags_ = 0;
std::string status_toast_;
float status_toast_timer_ = 0.0f;
ChampionshipState champ_;
HighscoreTable hiscores_;
sim::RaceSim race_sim_;
assets::LevelData viewer_level_;
// Track viewer camera
Vec3 viewer_pos_{14.0f, 6.0f, 92.0f};
float viewer_yaw_ = kPi;
float viewer_pitch_ = -0.25f;
// Intro & HUD timers
double intro_accum_ = 0.0;
double ui_time_ = 0.0;
std::array<std::string, 2> hud_banner_{};
std::array<float, 2> hud_banner_timer_{0.0f, 0.0f};
bool intro_turbo_played_ = false;
bool intro_explode_played_ = false;
};
} // namespace top_octane::game
+226
View File
@@ -0,0 +1,226 @@
#include "game/game_modes.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <sstream>
namespace top_octane::game {
namespace {
constexpr int kPointsTable[8] = {10, 6, 4, 3, 2, 1, 0, 0};
std::filesystem::path slot_path(const std::filesystem::path& pref_dir, int slot) {
char buf[32];
std::snprintf(buf, sizeof(buf), "champ_%02d.dat", std::clamp(slot, 0, 7));
return pref_dir / buf;
}
std::filesystem::path clone_path(const std::filesystem::path& pref_dir, int track_num) {
char buf[32];
std::snprintf(buf, sizeof(buf), "clone_0%d.bin", std::clamp(track_num, 1, 6));
return pref_dir / buf;
}
} // namespace
void ChampionshipState::start_new(const std::string& p_name, int vehicle_idx, int team_idx, int diff) {
active = true;
current_track = 1;
difficulty = std::clamp(diff, 0, 2);
player_vehicle = std::clamp(vehicle_idx, 0, 5);
player_team = std::clamp(team_idx, 0, 7);
player_name = p_name.empty() ? "PLAYER" : p_name;
overall_rating_pts = 0;
team_points.fill(0);
drivers[0] = {player_name, player_team, player_vehicle, 0, 0, 0};
for (int i = 1; i < 8; ++i) {
int ai = i - 1;
int team = (ai == player_team) ? ((ai + 1) % 8) : (ai % 8);
int veh = (ai * 5) % 6;
drivers[i] = {sim::kPilotNames[ai], team, veh, 0, 0, 0};
}
}
void ChampionshipState::record_race_results(const std::vector<sim::CraftState>& crafts) {
for (const auto& c : crafts) {
int rank = std::clamp(c.placement - 1, 0, 7);
int pts = kPointsTable[rank];
int slot = (c.id >= 0 && c.id < 8) ? c.id : 0;
drivers[slot].points += pts;
drivers[slot].kills += c.kills;
if (c.placement == 1) drivers[slot].wins += 1;
int tid = std::clamp(drivers[slot].team_idx, 0, 7);
team_points[tid] += pts;
if (c.is_human && c.player_index == 0) {
overall_rating_pts += pts * 12 + c.kills * 15 - c.deaths * 5 + (c.placement == 1 ? 40 : 0);
overall_rating_pts = std::max(0, overall_rating_pts);
}
}
++current_track;
}
std::string ChampionshipState::player_rating_title() const {
return sim::rating_for_score(overall_rating_pts);
}
bool ChampionshipState::save_slot(const std::filesystem::path& pref_dir, int slot) const {
std::error_code ec;
std::filesystem::create_directories(pref_dir, ec);
std::ofstream ofs(slot_path(pref_dir, slot), std::ios::trunc);
if (!ofs) return false;
ofs << "TOPOCTANE_CHAMP_V1\n"
<< (active ? 1 : 0) << " " << current_track << " " << difficulty << " "
<< player_vehicle << " " << player_team << " " << overall_rating_pts << "\n"
<< player_name << "\n";
for (int i = 0; i < 8; ++i) {
ofs << drivers[i].team_idx << " " << drivers[i].vehicle_idx << " "
<< drivers[i].points << " " << drivers[i].kills << " " << drivers[i].wins << " "
<< drivers[i].name << "\n";
}
for (int i = 0; i < 8; ++i) {
ofs << team_points[i] << (i == 7 ? "\n" : " ");
}
return ofs.good();
}
bool ChampionshipState::load_slot(const std::filesystem::path& pref_dir, int slot) {
std::ifstream ifs(slot_path(pref_dir, slot));
if (!ifs) return false;
std::string magic;
if (!std::getline(ifs, magic) || magic != "TOPOCTANE_CHAMP_V1") return false;
int act = 0;
if (!(ifs >> act >> current_track >> difficulty >> player_vehicle >> player_team >> overall_rating_pts)) {
return false;
}
active = (act != 0);
ifs.ignore(256, '\n');
if (!std::getline(ifs, player_name)) return false;
for (int i = 0; i < 8; ++i) {
if (!(ifs >> drivers[i].team_idx >> drivers[i].vehicle_idx >> drivers[i].points
>> drivers[i].kills >> drivers[i].wins)) {
return false;
}
std::string rest;
std::getline(ifs, rest);
size_t first = rest.find_first_not_of(' ');
drivers[i].name = (first == std::string::npos) ? "PILOT" : rest.substr(first);
}
for (int i = 0; i < 8; ++i) {
if (!(ifs >> team_points[i])) return false;
}
return true;
}
bool ChampionshipState::slot_exists(const std::filesystem::path& pref_dir, int slot) {
std::error_code ec;
return std::filesystem::is_regular_file(slot_path(pref_dir, slot), ec);
}
void HighscoreTable::clear() {
for (auto& t : tracks) {
t = TrackRecord{};
}
}
int HighscoreTable::submit_race(int track_num, const std::vector<sim::CraftState>& crafts) {
int idx = std::clamp(track_num - 1, 0, 5);
TrackRecord& rec = tracks[idx];
int flags = 0;
for (const auto& c : crafts) {
if (!c.is_human) continue;
if (c.best_lap_time > 0.5f && (rec.best_lap <= 0.0f || c.best_lap_time < rec.best_lap)) {
rec.best_lap = c.best_lap_time;
rec.best_lap_driver = c.pilot_name;
flags |= 1;
}
if (c.finished && c.race_time > 1.0f &&
(rec.best_race <= 0.0f || c.race_time < rec.best_race)) {
rec.best_race = c.race_time;
rec.best_race_driver = c.pilot_name;
flags |= 2;
}
}
return flags;
}
bool HighscoreTable::load(const std::filesystem::path& path) {
std::ifstream ifs(path);
if (!ifs) return false;
std::string magic;
if (!std::getline(ifs, magic) || magic != "TOPOCTANE_HISCORE_V1") return false;
for (int i = 0; i < 6; ++i) {
if (!(ifs >> tracks[i].best_lap >> tracks[i].best_race)) return false;
ifs.ignore(256, '\n');
if (!std::getline(ifs, tracks[i].best_lap_driver)) return false;
if (!std::getline(ifs, tracks[i].best_race_driver)) return false;
}
return true;
}
bool HighscoreTable::save(const std::filesystem::path& path) const {
std::error_code ec;
if (path.has_parent_path()) std::filesystem::create_directories(path.parent_path(), ec);
std::ofstream ofs(path, std::ios::trunc);
if (!ofs) return false;
ofs << "TOPOCTANE_HISCORE_V1\n" << std::setprecision(9);
for (int i = 0; i < 6; ++i) {
ofs << tracks[i].best_lap << " " << tracks[i].best_race << "\n"
<< tracks[i].best_lap_driver << "\n"
<< tracks[i].best_race_driver << "\n";
}
return ofs.good();
}
bool save_clone_recording(const std::filesystem::path& pref_dir, const sim::CloneRecording& rec) {
std::error_code ec;
std::filesystem::create_directories(pref_dir, ec);
std::ofstream ofs(clone_path(pref_dir, rec.track_number), std::ios::binary | std::ios::trunc);
if (!ofs) return false;
const uint32_t magic = 0x434C4E31u; // CLN1
uint32_t count = static_cast<uint32_t>(rec.frames.size());
ofs.write(reinterpret_cast<const char*>(&magic), sizeof(magic));
ofs.write(reinterpret_cast<const char*>(&rec.track_number), sizeof(rec.track_number));
ofs.write(reinterpret_cast<const char*>(&rec.vehicle_idx), sizeof(rec.vehicle_idx));
ofs.write(reinterpret_cast<const char*>(&rec.team_idx), sizeof(rec.team_idx));
ofs.write(reinterpret_cast<const char*>(&rec.best_race_time), sizeof(rec.best_race_time));
ofs.write(reinterpret_cast<const char*>(&count), sizeof(count));
if (count > 0) {
ofs.write(reinterpret_cast<const char*>(rec.frames.data()),
static_cast<std::streamsize>(count * sizeof(sim::CraftPose)));
}
return ofs.good();
}
bool load_clone_recording(const std::filesystem::path& pref_dir, int track_num,
sim::CloneRecording& out_rec) {
std::ifstream ifs(clone_path(pref_dir, track_num), std::ios::binary);
if (!ifs) return false;
uint32_t magic = 0, count = 0;
ifs.read(reinterpret_cast<char*>(&magic), sizeof(magic));
if (magic != 0x434C4E31u) return false;
ifs.read(reinterpret_cast<char*>(&out_rec.track_number), sizeof(out_rec.track_number));
ifs.read(reinterpret_cast<char*>(&out_rec.vehicle_idx), sizeof(out_rec.vehicle_idx));
ifs.read(reinterpret_cast<char*>(&out_rec.team_idx), sizeof(out_rec.team_idx));
ifs.read(reinterpret_cast<char*>(&out_rec.best_race_time), sizeof(out_rec.best_race_time));
ifs.read(reinterpret_cast<char*>(&count), sizeof(count));
if (!ifs || count > 36000) return false;
out_rec.frames.resize(count);
if (count > 0) {
ifs.read(reinterpret_cast<char*>(out_rec.frames.data()),
static_cast<std::streamsize>(count * sizeof(sim::CraftPose)));
}
return ifs.good();
}
} // namespace top_octane::game
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include "sim/race_sim.hpp"
#include "sim/vehicle_defs.hpp"
#include <array>
#include <filesystem>
#include <string>
#include <vector>
namespace top_octane::game {
struct DriverStanding {
std::string name;
int team_idx = 0;
int vehicle_idx = 0;
int points = 0;
int kills = 0;
int wins = 0;
};
struct ChampionshipState {
bool active = false;
int current_track = 1; // 1..6
int difficulty = 1;
int player_vehicle = 0;
int player_team = 7;
std::string player_name = "PLAYER";
int overall_rating_pts = 0;
std::array<DriverStanding, 8> drivers{};
std::array<int, 8> team_points{};
void start_new(const std::string& p_name, int vehicle_idx, int team_idx, int diff);
void record_race_results(const std::vector<sim::CraftState>& crafts);
bool is_complete() const { return current_track > 6; }
std::string player_rating_title() const;
bool save_slot(const std::filesystem::path& pref_dir, int slot) const;
bool load_slot(const std::filesystem::path& pref_dir, int slot);
static bool slot_exists(const std::filesystem::path& pref_dir, int slot);
};
struct TrackRecord {
float best_lap = 0.0f;
std::string best_lap_driver = "---";
float best_race = 0.0f;
std::string best_race_driver = "---";
};
struct HighscoreTable {
std::array<TrackRecord, 6> tracks{};
void clear();
// Returns bitmask: bit 0 = new fastest lap, bit 1 = new fastest race
int submit_race(int track_num, const std::vector<sim::CraftState>& crafts);
bool load(const std::filesystem::path& path);
bool save(const std::filesystem::path& path) const;
};
bool save_clone_recording(const std::filesystem::path& pref_dir, const sim::CloneRecording& rec);
bool load_clone_recording(const std::filesystem::path& pref_dir, int track_num,
sim::CloneRecording& out_rec);
} // namespace top_octane::game
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include "core/config.hpp"
namespace top_octane::game {
struct LocalizedStrings {
const char* single_race;
const char* death_match;
const char* clone_race;
const char* championship;
const char* split_screen;
const char* track_viewer;
const char* highscores;
const char* options;
const char* quit;
const char* select_track;
const char* select_car;
const char* laps;
const char* difficulty;
const char* opponents;
const char* weight;
const char* armour;
const char* speed;
const char* firepower;
const char* press_fire;
const char* continue_game;
const char* abort_game;
const char* final_lap;
const char* wrong_way;
const char* race_over;
const char* statistics;
const char* position;
const char* driver;
const char* time_hdr;
const char* best_lap;
const char* points;
};
inline const LocalizedStrings& get_strings(Language lang) {
static constexpr LocalizedStrings kEn{
"SINGLE RACE", "DEATH MATCH", "CLONE RACE", "CHAMPIONSHIP", "2P SPLIT SCREEN",
"TRACK VIEWER", "HIGHSCORES", "OPTIONS", "QUIT",
"SELECT TRACK", "SELECT VEHICLE", "LAPS", "DIFFICULTY", "OPPONENTS",
"WEIGHT", "ARMOUR", "SPEED", "FIREPOWER", "PRESS ENTER OR FIRE TO CONTINUE",
"CONTINUE GAME", "ABORT RACE", "FINAL LAP", "WRONG WAY", "RACE COMPLETE",
"STATISTICS", "POS", "DRIVER", "TIME", "BEST LAP", "PTS"
};
static constexpr LocalizedStrings kDe{
"EINZELRENNEN", "FREISTIL", "DOPPELGANGER", "MEISTERSCHAFT", "2P GETEILTER BILDSCHIRM",
"STRECKENSCHAU", "HIGHSCORES", "OPTIONEN", "BEENDEN",
"BAHN WAHLEN", "WAGEN WAHLEN", "RUNDEN", "SCHWIERIGKEIT", "GEGNER",
"GEWICHT", "PANZERUNG", "TEMPO", "FEUERKRAFT", "ENTER ODER FEUER DRUCKEN",
"WEITERSPIELEN", "RENNEN ABBRECHEN", "LETZTE RUNDE", "FALSCHE RICHTUNG", "RENNEN BEENDET",
"STATISTIK", "POS", "FAHRER", "ZEIT", "BESTE RUNDE", "PKT"
};
static constexpr LocalizedStrings kEs{
"CARRERA SIMPLE", "COMBATE MORTAL", "CARRERA CLON", "CAMPEONATO", "2P PANTALLA DIVIDIDA",
"VISOR DE PISTA", "RECORDS", "OPCIONES", "SALIR",
"ELEGIR PISTA", "ELEGIR VEHICULO", "VUELTAS", "DIFICULTAD", "RIVALES",
"PESO", "BLINDAJE", "VELOCIDAD", "POTENCIA", "PULSA ENTER O DISPARO",
"CONTINUAR", "ABANDONAR CARRERA", "ULTIMA VUELTA", "SENTIDO CONTRARIO", "FIN DE CARRERA",
"ESTADISTICAS", "POS", "PILOTO", "TIEMPO", "MEJOR VUELTA", "PTS"
};
static constexpr LocalizedStrings kFr{
"COURSE SIMPLE", "MATCH A MORT", "COURSE CLONE", "CHAMPIONNAT", "2P ECRAN PARTAGE",
"APERCU CIRCUIT", "MEILLEURS SCORES", "OPTIONS", "QUITTER",
"CHOISIR CIRCUIT", "CHOISIR VEHICULE", "TOURS", "DIFFICULTE", "ADVERSAIRES",
"POIDS", "BLINDAGE", "VITESSE", "PUISSANCE", "APPUYEZ SUR ENTREE OU TIR",
"CONTINUER", "ABANDONNER", "DERNIER TOUR", "MAUVAIS SENS", "COURSE TERMINEE",
"STATISTIQUES", "POS", "PILOTE", "TEMPS", "MEILLEUR TOUR", "PTS"
};
switch (lang) {
case Language::German: return kDe;
case Language::Spanish: return kEs;
case Language::French: return kFr;
default: return kEn;
}
}
} // namespace top_octane::game
+314
View File
@@ -0,0 +1,314 @@
#include "input/input_manager.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane {
namespace {
float shape_axis(int16_t raw, float deadzone, float curve, float sens) {
float norm = static_cast<float>(raw) / 32767.0f;
norm = std::clamp(norm, -1.0f, 1.0f);
float mag = std::abs(norm);
if (mag <= deadzone) return 0.0f;
float scaled = (mag - deadzone) / std::max(1.0f - deadzone, 0.001f);
float curved = std::pow(scaled, std::max(curve, 0.2f)) * sens;
return std::clamp(curved, 0.0f, 1.0f) * (norm < 0.0f ? -1.0f : 1.0f);
}
} // namespace
bool InputManager::init() {
if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) == 0) {
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC) != 0) {
LOG_WARN("GameController/Haptic init warning: %s", SDL_GetError());
}
}
int num = SDL_NumJoysticks();
for (int i = 0; i < num; ++i) {
if (SDL_IsGameController(i)) {
open_gamepad_by_device_index(i);
}
}
prev_keys_.fill(0);
curr_keys_.fill(0);
return true;
}
void InputManager::shutdown() {
for (int i = 0; i < kMaxGamepads; ++i) {
if (gamepads_[i]) {
SDL_GameControllerClose(gamepads_[i]);
gamepads_[i] = nullptr;
gamepad_ids_[i] = -1;
}
}
}
void InputManager::open_gamepad_by_device_index(int device_index) {
SDL_GameController* gc = SDL_GameControllerOpen(device_index);
if (!gc) return;
SDL_JoystickID id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gc));
for (int i = 0; i < kMaxGamepads; ++i) {
if (gamepads_[i] && gamepad_ids_[i] == id) {
SDL_GameControllerClose(gc);
return;
}
}
for (int i = 0; i < kMaxGamepads; ++i) {
if (!gamepads_[i]) {
gamepads_[i] = gc;
gamepad_ids_[i] = id;
LOG_INFO("Gamepad connected [slot %d]: %s", i, SDL_GameControllerName(gc));
return;
}
}
SDL_GameControllerClose(gc);
}
void InputManager::close_gamepad_by_instance_id(SDL_JoystickID instance_id) {
for (int i = 0; i < kMaxGamepads; ++i) {
if (gamepads_[i] && gamepad_ids_[i] == instance_id) {
LOG_INFO("Gamepad disconnected [slot %d]", i);
SDL_GameControllerClose(gamepads_[i]);
gamepads_[i] = nullptr;
gamepad_ids_[i] = -1;
return;
}
}
}
SDL_GameController* InputManager::get_player_gamepad(int player_idx, const GameConfig& cfg) const {
int slot = (player_idx == 0) ? cfg.p1_gamepad_index : cfg.p2_gamepad_index;
if (slot < 0 || slot >= kMaxGamepads) return nullptr;
return gamepads_[slot];
}
void InputManager::begin_frame() {
prev_keys_ = curr_keys_;
prev_gp_buttons_ = curr_gp_buttons_;
menu_ = MenuInput{};
}
void InputManager::handle_event(const SDL_Event& ev, GameConfig& cfg,
bool& out_quit, bool& out_toggle_fullscreen) {
switch (ev.type) {
case SDL_QUIT:
out_quit = true;
break;
case SDL_CONTROLLERDEVICEADDED:
open_gamepad_by_device_index(ev.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMOVED:
close_gamepad_by_instance_id(ev.cdevice.which);
break;
case SDL_KEYDOWN:
if (!ev.key.repeat) {
menu_.any_pressed = true;
SDL_Scancode sc = ev.key.keysym.scancode;
if (rebind_active_) {
if (sc != SDL_SCANCODE_ESCAPE) {
captured_scancode_ = static_cast<int>(sc);
} else {
rebind_active_ = false;
captured_scancode_ = 0;
}
return;
}
if ((ev.key.keysym.mod & KMOD_ALT) && sc == SDL_SCANCODE_RETURN) {
out_toggle_fullscreen = true;
}
if (sc == SDL_SCANCODE_F11) {
out_toggle_fullscreen = true;
}
}
break;
case SDL_CONTROLLERBUTTONDOWN:
menu_.any_pressed = true;
break;
case SDL_MOUSEMOTION:
if (cfg.mouse_steering) {
mouse_steer_accum_ = std::clamp(
mouse_steer_accum_ + static_cast<float>(ev.motion.xrel) * 0.008f * cfg.steering_sensitivity,
-1.0f, 1.0f);
}
break;
default:
break;
}
}
void InputManager::end_frame(const GameConfig& cfg) {
int num_keys = 0;
const uint8_t* kstate = SDL_GetKeyboardState(&num_keys);
int limit = std::min(num_keys, static_cast<int>(SDL_NUM_SCANCODES));
for (int i = 0; i < limit; ++i) {
curr_keys_[i] = kstate[i];
}
auto key_just = [&](int sc) -> bool {
if (sc <= 0 || sc >= SDL_NUM_SCANCODES) return false;
return curr_keys_[sc] && !prev_keys_[sc];
};
// Primary gamepad menu button tracking
SDL_GameController* gp = gamepads_[0];
if (!gp) {
for (auto* c : gamepads_) {
if (c) { gp = c; break; }
}
}
curr_gp_buttons_.fill(false);
if (gp) {
for (int b = 0; b < 15; ++b) {
curr_gp_buttons_[b] = SDL_GameControllerGetButton(gp, static_cast<SDL_GameControllerButton>(b)) != 0;
}
}
auto gp_just = [&](SDL_GameControllerButton b) -> bool {
int idx = static_cast<int>(b);
return curr_gp_buttons_[idx] && !prev_gp_buttons_[idx];
};
menu_.up = key_just(SDL_SCANCODE_UP) || key_just(SDL_SCANCODE_W) || gp_just(SDL_CONTROLLER_BUTTON_DPAD_UP);
menu_.down = key_just(SDL_SCANCODE_DOWN) || key_just(SDL_SCANCODE_S) || gp_just(SDL_CONTROLLER_BUTTON_DPAD_DOWN);
menu_.left = key_just(SDL_SCANCODE_LEFT) || key_just(SDL_SCANCODE_A) || gp_just(SDL_CONTROLLER_BUTTON_DPAD_LEFT);
menu_.right = key_just(SDL_SCANCODE_RIGHT) || key_just(SDL_SCANCODE_D) || gp_just(SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
menu_.confirm = key_just(SDL_SCANCODE_RETURN) || key_just(SDL_SCANCODE_KP_ENTER) ||
key_just(SDL_SCANCODE_SPACE) || gp_just(SDL_CONTROLLER_BUTTON_A);
menu_.back = key_just(SDL_SCANCODE_ESCAPE) || key_just(SDL_SCANCODE_BACKSPACE) ||
gp_just(SDL_CONTROLLER_BUTTON_B);
menu_.pause = key_just(SDL_SCANCODE_ESCAPE) || key_just(SDL_SCANCODE_P) ||
gp_just(SDL_CONTROLLER_BUTTON_START);
if (cfg.mouse_steering) {
// Gentle centering decay for mouse steering
mouse_steer_accum_ *= 0.88f;
if (std::abs(mouse_steer_accum_) < 0.01f) mouse_steer_accum_ = 0.0f;
} else {
mouse_steer_accum_ = 0.0f;
}
}
CraftInput InputManager::craft_input(int player_idx, const GameConfig& cfg,
bool allow_arrow_fallback) const {
CraftInput out;
auto key_down = [&](int sc) -> bool {
return sc > 0 && sc < SDL_NUM_SCANCODES && curr_keys_[sc] != 0;
};
auto key_just = [&](int sc) -> bool {
return sc > 0 && sc < SDL_NUM_SCANCODES && curr_keys_[sc] != 0 && prev_keys_[sc] == 0;
};
const KeyBindings& kb = cfg.keys;
if (player_idx == 0) {
if (key_down(kb.steer_left)) out.steer -= 1.0f;
if (key_down(kb.steer_right)) out.steer += 1.0f;
if (key_down(kb.accelerate)) out.throttle = 1.0f;
if (key_down(kb.brake)) out.brake = 1.0f;
out.boost = key_down(kb.boost);
out.fire_minigun = key_down(kb.fire_minigun);
out.fire_missile = key_down(kb.fire_missile);
out.toggle_autopilot_pressed = key_just(kb.autopilot);
out.cycle_camera_pressed = key_just(kb.camera_view);
// In 1P mode, support Arrow keys as ergonomic backup alongside WASD
if (allow_arrow_fallback) {
if (key_down(SDL_SCANCODE_LEFT)) out.steer -= 1.0f;
if (key_down(SDL_SCANCODE_RIGHT)) out.steer += 1.0f;
if (key_down(SDL_SCANCODE_UP)) out.throttle = 1.0f;
if (key_down(SDL_SCANCODE_DOWN)) out.brake = 1.0f;
}
out.steer = std::clamp(out.steer, -1.0f, 1.0f);
if (cfg.mouse_steering && std::abs(mouse_steer_accum_) > std::abs(out.steer)) {
out.steer = mouse_steer_accum_;
}
} else {
if (key_down(kb.p2_steer_left)) out.steer -= 1.0f;
if (key_down(kb.p2_steer_right)) out.steer += 1.0f;
if (key_down(kb.p2_accelerate)) out.throttle = 1.0f;
if (key_down(kb.p2_brake)) out.brake = 1.0f;
out.boost = key_down(kb.p2_boost);
out.fire_minigun = key_down(kb.p2_fire_minigun);
out.fire_missile = key_down(kb.p2_fire_missile);
}
if (SDL_GameController* gc = get_player_gamepad(player_idx, cfg)) {
float ax = shape_axis(SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTX),
cfg.gamepad_deadzone, cfg.steering_curve, cfg.steering_sensitivity);
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ax = -1.0f;
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) ax = 1.0f;
if (std::abs(ax) > std::abs(out.steer)) out.steer = ax;
float rt = static_cast<float>(SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) / 32767.0f;
float lt = static_cast<float>(SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_TRIGGERLEFT)) / 32767.0f;
if (rt > 0.08f) out.throttle = std::max(out.throttle, std::clamp(rt, 0.0f, 1.0f));
if (lt > 0.08f) out.brake = std::max(out.brake, std::clamp(lt, 0.0f, 1.0f));
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_A)) out.throttle = 1.0f;
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_B)) out.brake = 1.0f;
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_X) ||
SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {
out.boost = true;
}
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
out.fire_minigun = true;
}
if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_Y)) {
out.fire_missile = true;
}
}
out.steer = std::clamp(out.steer, -1.0f, 1.0f);
return out;
}
bool InputManager::consume_rebound_scancode(int& out_scancode) {
if (captured_scancode_ != 0) {
out_scancode = captured_scancode_;
captured_scancode_ = 0;
rebind_active_ = false;
return true;
}
return false;
}
void InputManager::trigger_rumble(int player_idx, float low_freq, float high_freq,
uint32_t duration_ms, const GameConfig& cfg) {
if (!cfg.rumble_enabled) return;
if (SDL_GameController* gc = get_player_gamepad(player_idx, cfg)) {
uint16_t lo = static_cast<uint16_t>(std::clamp(low_freq, 0.0f, 1.0f) * 65535.0f);
uint16_t hi = static_cast<uint16_t>(std::clamp(high_freq, 0.0f, 1.0f) * 65535.0f);
SDL_GameControllerRumble(gc, lo, hi, duration_ms);
}
}
int InputManager::connected_gamepad_count() const {
int c = 0;
for (auto* gc : gamepads_) {
if (gc) ++c;
}
return c;
}
std::string InputManager::gamepad_name(int slot) const {
if (slot < 0 || slot >= kMaxGamepads || !gamepads_[slot]) return "None";
const char* n = SDL_GameControllerName(gamepads_[slot]);
return n ? n : "Gamepad";
}
std::string InputManager::scancode_name(int scancode) {
if (scancode <= 0 || scancode >= SDL_NUM_SCANCODES) return "NONE";
const char* n = SDL_GetScancodeName(static_cast<SDL_Scancode>(scancode));
return (n && *n) ? std::string(n) : "KEY";
}
} // namespace top_octane
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include "core/config.hpp"
#include <SDL.h>
#include <array>
#include <cstdint>
#include <string>
namespace top_octane {
struct CraftInput {
float steer = 0.0f; // -1.0 (left) .. +1.0 (right)
float throttle = 0.0f; // 0.0 .. 1.0
float brake = 0.0f; // 0.0 .. 1.0
bool boost = false;
bool fire_minigun = false;
bool fire_missile = false;
bool toggle_autopilot_pressed = false;
bool cycle_camera_pressed = false;
};
struct MenuInput {
bool up = false;
bool down = false;
bool left = false;
bool right = false;
bool confirm = false;
bool back = false;
bool pause = false;
bool any_pressed = false;
};
class InputManager {
public:
static constexpr int kMaxGamepads = 4;
bool init();
void shutdown();
// Call before SDL_PollEvent loop each frame
void begin_frame();
// Feed every polled SDL_Event here
void handle_event(const SDL_Event& ev, GameConfig& cfg, bool& out_quit, bool& out_toggle_fullscreen);
// Call after SDL_PollEvent loop each frame to update states
void end_frame(const GameConfig& cfg);
CraftInput craft_input(int player_idx, const GameConfig& cfg, bool allow_arrow_fallback = true) const;
const MenuInput& menu_input() const { return menu_; }
// Live key rebinding support
void start_rebind() { rebind_active_ = true; captured_scancode_ = 0; }
void cancel_rebind() { rebind_active_ = false; captured_scancode_ = 0; }
bool is_rebinding() const { return rebind_active_; }
bool consume_rebound_scancode(int& out_scancode);
// Rumble / Haptics
void trigger_rumble(int player_idx, float low_freq, float high_freq, uint32_t duration_ms,
const GameConfig& cfg);
int connected_gamepad_count() const;
std::string gamepad_name(int slot) const;
static std::string scancode_name(int scancode);
private:
void open_gamepad_by_device_index(int device_index);
void close_gamepad_by_instance_id(SDL_JoystickID instance_id);
SDL_GameController* get_player_gamepad(int player_idx, const GameConfig& cfg) const;
std::array<SDL_GameController*, kMaxGamepads> gamepads_{};
std::array<SDL_JoystickID, kMaxGamepads> gamepad_ids_{{-1, -1, -1, -1}};
std::array<uint8_t, SDL_NUM_SCANCODES> prev_keys_{};
std::array<uint8_t, SDL_NUM_SCANCODES> curr_keys_{};
std::array<bool, 16> prev_gp_buttons_{};
std::array<bool, 16> curr_gp_buttons_{};
float mouse_steer_accum_ = 0.0f;
MenuInput menu_{};
bool rebind_active_ = false;
int captured_scancode_ = 0;
};
} // namespace top_octane
+66
View File
@@ -0,0 +1,66 @@
#include "core/log.hpp"
#include "game/game_app.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace top_octane;
namespace {
void print_usage(const char* argv0) {
std::cout << "Top-Octane (Modern Cross-Platform SDL2 + OpenGL 3.3 Port of Hi-Octane)\n"
<< "Usage: " << argv0 << " [options]\n"
<< " --data-dir <path> Path to read-only assets folder (default: ./data)\n"
<< " --track <1..6> Launch straight into race on track 1..6\n"
<< " --track-viewer <1..6> Open interactive 3D track viewer for track 1..6\n"
<< " --classic Start in 4:3 Classic palette visual mode\n"
<< " --fullscreen Start in borderless fullscreen\n"
<< " --music-backend <opl3|sf|custom> Select music synth backend\n"
<< " --skip-intro Skip INTRO.DAT movie\n"
<< " --smoke-test <frames> Render N frames and exit cleanly\n"
<< " --help Show this help\n";
}
} // namespace
int main(int argc, char** argv) {
game::LaunchOptions opts;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--help") == 0 || std::strcmp(argv[i], "-h") == 0) {
print_usage(argv[0]);
return 0;
} else if (std::strcmp(argv[i], "--data-dir") == 0 && i + 1 < argc) {
opts.data_dir = argv[++i];
} else if (std::strcmp(argv[i], "--track") == 0 && i + 1 < argc) {
opts.start_track = std::atoi(argv[++i]);
} else if (std::strcmp(argv[i], "--track-viewer") == 0 && i + 1 < argc) {
opts.start_track = std::atoi(argv[++i]);
opts.track_viewer = true;
} else if (std::strcmp(argv[i], "--classic") == 0) {
opts.force_classic = true;
} else if (std::strcmp(argv[i], "--fullscreen") == 0) {
opts.force_fullscreen = true;
} else if (std::strcmp(argv[i], "--music-backend") == 0 && i + 1 < argc) {
const char* b = argv[++i];
if (std::strcmp(b, "opl3") == 0) opts.force_backend = 0;
else if (std::strcmp(b, "sf") == 0 || std::strcmp(b, "soundfont") == 0) opts.force_backend = 1;
else if (std::strcmp(b, "custom") == 0) opts.force_backend = 2;
} else if (std::strcmp(argv[i], "--skip-intro") == 0) {
opts.skip_intro = true;
} else if (std::strcmp(argv[i], "--smoke-test") == 0 && i + 1 < argc) {
opts.smoke_test_frames = std::atoi(argv[++i]);
} else {
LOG_WARN("Unknown argument: %s", argv[i]);
}
}
game::GameApp app;
if (!app.init(opts)) {
return 1;
}
int rc = app.run();
app.shutdown();
return rc;
}
+137
View File
@@ -0,0 +1,137 @@
#include "render/gl_api.hpp"
#include "core/log.hpp"
namespace top_octane::gl {
PFNGLACTIVETEXTUREPROC ActiveTexture = nullptr;
PFNGLTEXIMAGE3DPROC TexImage3D = nullptr;
PFNGLTEXSUBIMAGE3DPROC TexSubImage3D = nullptr;
PFNGLGENERATEMIPMAPPROC GenerateMipmap = nullptr;
PFNGLGENBUFFERSPROC GenBuffers = nullptr;
PFNGLDELETEBUFFERSPROC DeleteBuffers = nullptr;
PFNGLBINDBUFFERPROC BindBuffer = nullptr;
PFNGLBUFFERDATAPROC BufferData = nullptr;
PFNGLBUFFERSUBDATAPROC BufferSubData = nullptr;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays = nullptr;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays = nullptr;
PFNGLBINDVERTEXARRAYPROC BindVertexArray = nullptr;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray = nullptr;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer = nullptr;
PFNGLCREATESHADERPROC CreateShader = nullptr;
PFNGLDELETESHADERPROC DeleteShader = nullptr;
PFNGLSHADERSOURCEPROC ShaderSource = nullptr;
PFNGLCOMPILESHADERPROC CompileShader = nullptr;
PFNGLGETSHADERIVPROC GetShaderiv = nullptr;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog = nullptr;
PFNGLCREATEPROGRAMPROC CreateProgram = nullptr;
PFNGLDELETEPROGRAMPROC DeleteProgram = nullptr;
PFNGLATTACHSHADERPROC AttachShader = nullptr;
PFNGLLINKPROGRAMPROC LinkProgram = nullptr;
PFNGLGETPROGRAMIVPROC GetProgramiv = nullptr;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog = nullptr;
PFNGLUSEPROGRAMPROC UseProgram = nullptr;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation = nullptr;
PFNGLUNIFORM1IPROC Uniform1i = nullptr;
PFNGLUNIFORM1FPROC Uniform1f = nullptr;
PFNGLUNIFORM2FPROC Uniform2f = nullptr;
PFNGLUNIFORM3FPROC Uniform3f = nullptr;
PFNGLUNIFORM4FPROC Uniform4f = nullptr;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv = nullptr;
PFNGLGENFRAMEBUFFERSPROC GenFramebuffers = nullptr;
PFNGLDELETEFRAMEBUFFERSPROC DeleteFramebuffers = nullptr;
PFNGLBINDFRAMEBUFFERPROC BindFramebuffer = nullptr;
PFNGLFRAMEBUFFERTEXTURE2DPROC FramebufferTexture2D = nullptr;
PFNGLGENRENDERBUFFERSPROC GenRenderbuffers = nullptr;
PFNGLDELETERENDERBUFFERSPROC DeleteRenderbuffers = nullptr;
PFNGLBINDRENDERBUFFERPROC BindRenderbuffer = nullptr;
PFNGLRENDERBUFFERSTORAGEPROC RenderbufferStorage = nullptr;
PFNGLFRAMEBUFFERRENDERBUFFERPROC FramebufferRenderbuffer = nullptr;
PFNGLCHECKFRAMEBUFFERSTATUSPROC CheckFramebufferStatus = nullptr;
namespace {
bool g_loaded = false;
template <typename T>
bool load_fn(T& out, const char* name) {
out = reinterpret_cast<T>(SDL_GL_GetProcAddress(name));
if (!out) {
LOG_ERROR("Failed to load OpenGL function: %s", name);
return false;
}
return true;
}
} // namespace
bool init() {
bool ok = true;
ok &= load_fn(ActiveTexture, "glActiveTexture");
ok &= load_fn(TexImage3D, "glTexImage3D");
ok &= load_fn(TexSubImage3D, "glTexSubImage3D");
ok &= load_fn(GenerateMipmap, "glGenerateMipmap");
ok &= load_fn(GenBuffers, "glGenBuffers");
ok &= load_fn(DeleteBuffers, "glDeleteBuffers");
ok &= load_fn(BindBuffer, "glBindBuffer");
ok &= load_fn(BufferData, "glBufferData");
ok &= load_fn(BufferSubData, "glBufferSubData");
ok &= load_fn(GenVertexArrays, "glGenVertexArrays");
ok &= load_fn(DeleteVertexArrays, "glDeleteVertexArrays");
ok &= load_fn(BindVertexArray, "glBindVertexArray");
ok &= load_fn(EnableVertexAttribArray, "glEnableVertexAttribArray");
ok &= load_fn(VertexAttribPointer, "glVertexAttribPointer");
ok &= load_fn(CreateShader, "glCreateShader");
ok &= load_fn(DeleteShader, "glDeleteShader");
ok &= load_fn(ShaderSource, "glShaderSource");
ok &= load_fn(CompileShader, "glCompileShader");
ok &= load_fn(GetShaderiv, "glGetShaderiv");
ok &= load_fn(GetShaderInfoLog, "glGetShaderInfoLog");
ok &= load_fn(CreateProgram, "glCreateProgram");
ok &= load_fn(DeleteProgram, "glDeleteProgram");
ok &= load_fn(AttachShader, "glAttachShader");
ok &= load_fn(LinkProgram, "glLinkProgram");
ok &= load_fn(GetProgramiv, "glGetProgramiv");
ok &= load_fn(GetProgramInfoLog, "glGetProgramInfoLog");
ok &= load_fn(UseProgram, "glUseProgram");
ok &= load_fn(GetUniformLocation, "glGetUniformLocation");
ok &= load_fn(Uniform1i, "glUniform1i");
ok &= load_fn(Uniform1f, "glUniform1f");
ok &= load_fn(Uniform2f, "glUniform2f");
ok &= load_fn(Uniform3f, "glUniform3f");
ok &= load_fn(Uniform4f, "glUniform4f");
ok &= load_fn(UniformMatrix4fv, "glUniformMatrix4fv");
ok &= load_fn(GenFramebuffers, "glGenFramebuffers");
ok &= load_fn(DeleteFramebuffers, "glDeleteFramebuffers");
ok &= load_fn(BindFramebuffer, "glBindFramebuffer");
ok &= load_fn(FramebufferTexture2D, "glFramebufferTexture2D");
ok &= load_fn(GenRenderbuffers, "glGenRenderbuffers");
ok &= load_fn(DeleteRenderbuffers, "glDeleteRenderbuffers");
ok &= load_fn(BindRenderbuffer, "glBindRenderbuffer");
ok &= load_fn(RenderbufferStorage, "glRenderbufferStorage");
ok &= load_fn(FramebufferRenderbuffer, "glFramebufferRenderbuffer");
ok &= load_fn(CheckFramebufferStatus, "glCheckFramebufferStatus");
g_loaded = ok;
if (ok) {
const char* ver = reinterpret_cast<const char*>(glGetString(GL_VERSION));
const char* ren = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
LOG_INFO("OpenGL initialized: %s | %s", ver ? ver : "?", ren ? ren : "?");
}
return ok;
}
bool is_loaded() { return g_loaded; }
} // namespace top_octane::gl
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <SDL.h>
#include <SDL_opengl.h>
namespace top_octane::gl {
bool init();
bool is_loaded();
// OpenGL 1.3 - 3.3 Core dynamic function pointers loaded via SDL_GL_GetProcAddress
extern PFNGLACTIVETEXTUREPROC ActiveTexture;
extern PFNGLTEXIMAGE3DPROC TexImage3D;
extern PFNGLTEXSUBIMAGE3DPROC TexSubImage3D;
extern PFNGLGENERATEMIPMAPPROC GenerateMipmap;
extern PFNGLGENBUFFERSPROC GenBuffers;
extern PFNGLDELETEBUFFERSPROC DeleteBuffers;
extern PFNGLBINDBUFFERPROC BindBuffer;
extern PFNGLBUFFERDATAPROC BufferData;
extern PFNGLBUFFERSUBDATAPROC BufferSubData;
extern PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
extern PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
extern PFNGLBINDVERTEXARRAYPROC BindVertexArray;
extern PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
extern PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
extern PFNGLCREATESHADERPROC CreateShader;
extern PFNGLDELETESHADERPROC DeleteShader;
extern PFNGLSHADERSOURCEPROC ShaderSource;
extern PFNGLCOMPILESHADERPROC CompileShader;
extern PFNGLGETSHADERIVPROC GetShaderiv;
extern PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
extern PFNGLCREATEPROGRAMPROC CreateProgram;
extern PFNGLDELETEPROGRAMPROC DeleteProgram;
extern PFNGLATTACHSHADERPROC AttachShader;
extern PFNGLLINKPROGRAMPROC LinkProgram;
extern PFNGLGETPROGRAMIVPROC GetProgramiv;
extern PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
extern PFNGLUSEPROGRAMPROC UseProgram;
extern PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
extern PFNGLUNIFORM1IPROC Uniform1i;
extern PFNGLUNIFORM1FPROC Uniform1f;
extern PFNGLUNIFORM2FPROC Uniform2f;
extern PFNGLUNIFORM3FPROC Uniform3f;
extern PFNGLUNIFORM4FPROC Uniform4f;
extern PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
extern PFNGLGENFRAMEBUFFERSPROC GenFramebuffers;
extern PFNGLDELETEFRAMEBUFFERSPROC DeleteFramebuffers;
extern PFNGLBINDFRAMEBUFFERPROC BindFramebuffer;
extern PFNGLFRAMEBUFFERTEXTURE2DPROC FramebufferTexture2D;
extern PFNGLGENRENDERBUFFERSPROC GenRenderbuffers;
extern PFNGLDELETERENDERBUFFERSPROC DeleteRenderbuffers;
extern PFNGLBINDRENDERBUFFERPROC BindRenderbuffer;
extern PFNGLRENDERBUFFERSTORAGEPROC RenderbufferStorage;
extern PFNGLFRAMEBUFFERRENDERBUFFERPROC FramebufferRenderbuffer;
extern PFNGLCHECKFRAMEBUFFERSTATUSPROC CheckFramebufferStatus;
} // namespace top_octane::gl
+109
View File
@@ -0,0 +1,109 @@
#include "render/shader.hpp"
#include "core/log.hpp"
#include <vector>
namespace top_octane::render {
namespace {
GLuint compile_stage(GLenum stage, const char* src, const char* debug_name) {
GLuint sh = gl::CreateShader(stage);
gl::ShaderSource(sh, 1, &src, nullptr);
gl::CompileShader(sh);
GLint status = GL_FALSE;
gl::GetShaderiv(sh, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
GLint len = 0;
gl::GetShaderiv(sh, GL_INFO_LOG_LENGTH, &len);
std::vector<char> buf(static_cast<size_t>(len > 1 ? len : 1), '\0');
gl::GetShaderInfoLog(sh, len, nullptr, buf.data());
LOG_ERROR("Shader compile failed (%s, stage=%u):\n%s", debug_name, stage, buf.data());
gl::DeleteShader(sh);
return 0;
}
return sh;
}
} // namespace
ShaderProgram::~ShaderProgram() {
destroy();
}
bool ShaderProgram::build(const char* vs_src, const char* fs_src, const char* debug_name) {
destroy();
GLuint vs = compile_stage(GL_VERTEX_SHADER, vs_src, debug_name);
if (!vs) return false;
GLuint fs = compile_stage(GL_FRAGMENT_SHADER, fs_src, debug_name);
if (!fs) {
gl::DeleteShader(vs);
return false;
}
GLuint prog = gl::CreateProgram();
gl::AttachShader(prog, vs);
gl::AttachShader(prog, fs);
gl::LinkProgram(prog);
gl::DeleteShader(vs);
gl::DeleteShader(fs);
GLint linked = GL_FALSE;
gl::GetProgramiv(prog, GL_LINK_STATUS, &linked);
if (linked != GL_TRUE) {
GLint len = 0;
gl::GetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
std::vector<char> buf(static_cast<size_t>(len > 1 ? len : 1), '\0');
gl::GetProgramInfoLog(prog, len, nullptr, buf.data());
LOG_ERROR("Shader link failed (%s):\n%s", debug_name, buf.data());
gl::DeleteProgram(prog);
return false;
}
program_ = prog;
return true;
}
void ShaderProgram::destroy() {
if (program_ != 0 && gl::is_loaded()) {
gl::DeleteProgram(program_);
}
program_ = 0;
}
void ShaderProgram::use() const {
gl::UseProgram(program_);
}
void ShaderProgram::set_int(const char* name, int val) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::Uniform1i(loc, val);
}
void ShaderProgram::set_float(const char* name, float val) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::Uniform1f(loc, val);
}
void ShaderProgram::set_vec2(const char* name, float x, float y) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::Uniform2f(loc, x, y);
}
void ShaderProgram::set_vec3(const char* name, const Vec3& v) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::Uniform3f(loc, v.x, v.y, v.z);
}
void ShaderProgram::set_vec4(const char* name, const Vec4& v) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::Uniform4f(loc, v.x, v.y, v.z, v.w);
}
void ShaderProgram::set_mat4(const char* name, const Mat4& m) const {
GLint loc = gl::GetUniformLocation(program_, name);
if (loc >= 0) gl::UniformMatrix4fv(loc, 1, GL_FALSE, m.m);
}
} // namespace top_octane::render
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "core/math.hpp"
#include "render/gl_api.hpp"
#include <string>
namespace top_octane::render {
class ShaderProgram {
public:
ShaderProgram() = default;
~ShaderProgram();
ShaderProgram(const ShaderProgram&) = delete;
ShaderProgram& operator=(const ShaderProgram&) = delete;
bool build(const char* vs_src, const char* fs_src, const char* debug_name = "shader");
void destroy();
void use() const;
GLuint id() const { return program_; }
void set_int(const char* name, int val) const;
void set_float(const char* name, float val) const;
void set_vec2(const char* name, float x, float y) const;
void set_vec3(const char* name, const Vec3& v) const;
void set_vec4(const char* name, const Vec4& v) const;
void set_mat4(const char* name, const Mat4& m) const;
private:
GLuint program_ = 0;
};
} // namespace top_octane::render
+424
View File
@@ -0,0 +1,424 @@
#include "render/ui_renderer.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <array>
#include <cctype>
#include <cmath>
namespace top_octane::render {
namespace {
constexpr const char* kUiVS = R"glsl(
#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec2 aUv;
layout(location = 2) in vec4 aColor;
uniform mat4 uOrtho;
out vec2 vUv;
out vec4 vColor;
void main() {
vUv = aUv;
vColor = aColor;
gl_Position = uOrtho * vec4(aPos, 0.0, 1.0);
}
)glsl";
constexpr const char* kUiFS = R"glsl(
#version 330 core
in vec2 vUv;
in vec4 vColor;
uniform sampler2D uTex;
out vec4 FragColor;
void main() {
vec4 t = texture(uTex, vUv);
vec4 res = t * vColor;
if (res.a < 0.01) discard;
FragColor = res;
}
)glsl";
// Compact 5x7 bitmap font for ASCII 32..95 (7 rows x 5 bits per glyph)
struct Glyph5x7 {
uint8_t rows[7];
};
const Glyph5x7& get_glyph(char ch) {
unsigned char uc = static_cast<unsigned char>(std::toupper(static_cast<unsigned char>(ch)));
static constexpr Glyph5x7 kBlank{{0, 0, 0, 0, 0, 0, 0}};
static constexpr Glyph5x7 kTable[64] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00}}, // ' ' 32
{{0x04,0x04,0x04,0x04,0x04,0x00,0x04}}, // '!' 33
{{0x0A,0x0A,0x00,0x00,0x00,0x00,0x00}}, // '"' 34
{{0x0A,0x1F,0x0A,0x0A,0x1F,0x0A,0x00}}, // '#' 35
{{0x04,0x0F,0x14,0x0E,0x05,0x1E,0x04}}, // '$' 36
{{0x18,0x19,0x02,0x04,0x08,0x13,0x03}}, // '%' 37
{{0x0C,0x12,0x14,0x08,0x15,0x12,0x0D}}, // '&' 38
{{0x06,0x04,0x08,0x00,0x00,0x00,0x00}}, // ''' 39
{{0x02,0x04,0x08,0x08,0x08,0x04,0x02}}, // '(' 40
{{0x08,0x04,0x02,0x02,0x02,0x04,0x08}}, // ')' 41
{{0x00,0x0A,0x04,0x1F,0x04,0x0A,0x00}}, // '*' 42
{{0x00,0x04,0x04,0x1F,0x04,0x04,0x00}}, // '+' 43
{{0x00,0x00,0x00,0x00,0x06,0x04,0x08}}, // ',' 44
{{0x00,0x00,0x00,0x1F,0x00,0x00,0x00}}, // '-' 45
{{0x00,0x00,0x00,0x00,0x00,0x06,0x06}}, // '.' 46
{{0x01,0x01,0x02,0x04,0x08,0x10,0x10}}, // '/' 47
{{0x0E,0x11,0x13,0x15,0x19,0x11,0x0E}}, // '0' 48
{{0x04,0x0C,0x04,0x04,0x04,0x04,0x0E}}, // '1' 49
{{0x0E,0x11,0x01,0x02,0x04,0x08,0x1F}}, // '2' 50
{{0x1F,0x02,0x04,0x02,0x01,0x11,0x0E}}, // '3' 51
{{0x02,0x06,0x0A,0x12,0x1F,0x02,0x02}}, // '4' 52
{{0x1F,0x10,0x1E,0x01,0x01,0x11,0x0E}}, // '5' 53
{{0x06,0x08,0x10,0x1E,0x11,0x11,0x0E}}, // '6' 54
{{0x1F,0x01,0x02,0x04,0x08,0x08,0x08}}, // '7' 55
{{0x0E,0x11,0x11,0x0E,0x11,0x11,0x0E}}, // '8' 56
{{0x0E,0x11,0x11,0x0F,0x01,0x02,0x0C}}, // '9' 57
{{0x00,0x06,0x06,0x00,0x06,0x06,0x00}}, // ':' 58
{{0x00,0x06,0x06,0x00,0x06,0x04,0x08}}, // ';' 59
{{0x02,0x04,0x08,0x10,0x08,0x04,0x02}}, // '<' 60
{{0x00,0x00,0x1F,0x00,0x1F,0x00,0x00}}, // '=' 61
{{0x08,0x04,0x02,0x01,0x02,0x04,0x08}}, // '>' 62
{{0x0E,0x11,0x01,0x02,0x04,0x00,0x04}}, // '?' 63
{{0x0E,0x11,0x17,0x15,0x17,0x10,0x0E}}, // '@' 64
{{0x0E,0x11,0x11,0x1F,0x11,0x11,0x11}}, // 'A' 65
{{0x1E,0x11,0x11,0x1E,0x11,0x11,0x1E}}, // 'B' 66
{{0x0E,0x11,0x10,0x10,0x10,0x11,0x0E}}, // 'C' 67
{{0x1E,0x11,0x11,0x11,0x11,0x11,0x1E}}, // 'D' 68
{{0x1F,0x10,0x10,0x1E,0x10,0x10,0x1F}}, // 'E' 69
{{0x1F,0x10,0x10,0x1E,0x10,0x10,0x10}}, // 'F' 70
{{0x0E,0x11,0x10,0x17,0x11,0x11,0x0F}}, // 'G' 71
{{0x11,0x11,0x11,0x1F,0x11,0x11,0x11}}, // 'H' 72
{{0x0E,0x04,0x04,0x04,0x04,0x04,0x0E}}, // 'I' 73
{{0x07,0x02,0x02,0x02,0x02,0x12,0x0C}}, // 'J' 74
{{0x11,0x12,0x14,0x18,0x14,0x12,0x11}}, // 'K' 75
{{0x10,0x10,0x10,0x10,0x10,0x10,0x1F}}, // 'L' 76
{{0x11,0x1B,0x15,0x15,0x11,0x11,0x11}}, // 'M' 77
{{0x11,0x19,0x15,0x13,0x11,0x11,0x11}}, // 'N' 78
{{0x0E,0x11,0x11,0x11,0x11,0x11,0x0E}}, // 'O' 79
{{0x1E,0x11,0x11,0x1E,0x10,0x10,0x10}}, // 'P' 80
{{0x0E,0x11,0x11,0x11,0x15,0x12,0x0D}}, // 'Q' 81
{{0x1E,0x11,0x11,0x1E,0x14,0x12,0x11}}, // 'R' 82
{{0x0F,0x10,0x10,0x0E,0x01,0x01,0x1E}}, // 'S' 83
{{0x1F,0x04,0x04,0x04,0x04,0x04,0x04}}, // 'T' 84
{{0x11,0x11,0x11,0x11,0x11,0x11,0x0E}}, // 'U' 85
{{0x11,0x11,0x11,0x11,0x11,0x0A,0x04}}, // 'V' 86
{{0x11,0x11,0x11,0x15,0x15,0x1B,0x11}}, // 'W' 87
{{0x11,0x11,0x0A,0x04,0x0A,0x11,0x11}}, // 'X' 88
{{0x11,0x11,0x0A,0x04,0x04,0x04,0x04}}, // 'Y' 89
{{0x1F,0x01,0x02,0x04,0x08,0x10,0x1F}}, // 'Z' 90
{{0x0E,0x08,0x08,0x08,0x08,0x08,0x0E}}, // '[' 91
{{0x10,0x10,0x08,0x04,0x02,0x01,0x01}}, // '\' 92
{{0x0E,0x02,0x02,0x02,0x02,0x02,0x0E}}, // ']' 93
{{0x04,0x0A,0x11,0x00,0x00,0x00,0x00}}, // '^' 94
{{0x00,0x00,0x00,0x00,0x00,0x00,0x1F}}, // '_' 95
};
if (uc >= 32 && uc < 96) return kTable[uc - 32];
return kBlank;
}
} // namespace
UiRenderer::~UiRenderer() {
shutdown();
}
void UiRenderer::upload_rgba(GLuint& tex, int w, int h, const uint8_t* rgba, bool linear) {
if (!tex) glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
GLint f = linear ? GL_LINEAR : GL_NEAREST;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, f);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, f);
}
void UiRenderer::load_bank(const Vfs& vfs, const assets::Palette& pal,
const std::string& key, const std::string& stem) {
assets::SpriteBank sb;
if (!sb.load(vfs, "DATA/" + stem + ".DAT", "DATA/" + stem + ".TAB", pal)) {
LOG_WARN("Optional sprite bank failed to load: %s", stem.c_str());
return;
}
auto& vec = banks_[key];
vec.resize(sb.sprites.size());
for (size_t i = 0; i < sb.sprites.size(); ++i) {
const auto& sp = sb.sprites[i];
if (sp.width > 0 && sp.height > 0 && !sp.rgba.empty()) {
vec[i].width = sp.width;
vec[i].height = sp.height;
upload_rgba(vec[i].tex, sp.width, sp.height, sp.rgba.data(), true);
}
}
}
bool UiRenderer::init(const Vfs& vfs, const assets::Palette& pal) {
if (initialized_) return true;
if (!ui_shader_.build(kUiVS, kUiFS, "ui")) return false;
static constexpr uint8_t kWhite[4] = {255, 255, 255, 255};
upload_rgba(white_tex_, 1, 1, kWhite, false);
gl::GenVertexArrays(1, &vao_);
gl::GenBuffers(1, &vbo_);
gl::BindVertexArray(vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, vbo_);
gl::BufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(UiVertex), nullptr);
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(UiVertex),
reinterpret_cast<void*>(2 * sizeof(float)));
gl::EnableVertexAttribArray(2);
gl::VertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(UiVertex),
reinterpret_cast<void*>(4 * sizeof(float)));
gl::BindVertexArray(0);
// Load key Hi-Res Bullfrog screens & banks
auto load_scr = [&](const std::string& key, const std::string& path, int w, int h) {
assets::SpriteImage img;
if (assets::load_raw_screen(vfs, path, w, h, pal, img)) {
GpuSpriteTex gt;
gt.width = w;
gt.height = h;
upload_rgba(gt.tex, w, h, img.rgba.data(), true);
screens_[key] = gt;
}
};
load_scr("title", "DATA/TITLE.DAT", 320, 200);
load_scr("oscr", "DATA/OSCR0-1.DAT", 640, 480);
load_scr("onet", "DATA/ONET0-1.DAT", 640, 480);
load_bank(vfs, pal, "logo", "LOGO0-1");
load_bank(vfs, pal, "panel", "PANEL0-1");
load_bank(vfs, pal, "track", "TRACK0-1");
initialized_ = true;
return true;
}
void UiRenderer::shutdown() {
if (!initialized_) return;
if (white_tex_) glDeleteTextures(1, &white_tex_);
if (stream_tex_) glDeleteTextures(1, &stream_tex_);
for (auto& [k, s] : screens_) {
if (s.tex) glDeleteTextures(1, &s.tex);
}
for (auto& [k, vec] : banks_) {
for (auto& s : vec) {
if (s.tex) glDeleteTextures(1, &s.tex);
}
}
screens_.clear();
banks_.clear();
if (gl::is_loaded()) {
if (vao_) gl::DeleteVertexArrays(1, &vao_);
if (vbo_) gl::DeleteBuffers(1, &vbo_);
}
white_tex_ = stream_tex_ = vao_ = vbo_ = 0;
ui_shader_.destroy();
initialized_ = false;
}
void UiRenderer::begin(int screen_w, int screen_h) {
screen_w_ = std::max(screen_w, 1);
screen_h_ = std::max(screen_h, 1);
verts_.clear();
batches_.clear();
}
void UiRenderer::push_quad(GLuint tex, float x0, float y0, float x1, float y1,
float u0, float v0, float u1, float v1, const Vec4& c) {
uint32_t start = static_cast<uint32_t>(verts_.size());
verts_.push_back({x0, y0, u0, v0, c.x, c.y, c.z, c.w});
verts_.push_back({x1, y0, u1, v0, c.x, c.y, c.z, c.w});
verts_.push_back({x1, y1, u1, v1, c.x, c.y, c.z, c.w});
verts_.push_back({x0, y0, u0, v0, c.x, c.y, c.z, c.w});
verts_.push_back({x1, y1, u1, v1, c.x, c.y, c.z, c.w});
verts_.push_back({x0, y1, u0, v1, c.x, c.y, c.z, c.w});
if (!batches_.empty() && batches_.back().tex == tex) {
batches_.back().count += 6;
} else {
batches_.push_back({tex, start, 6});
}
}
void UiRenderer::end() {
if (verts_.empty()) return;
glViewport(0, 0, screen_w_, screen_h_);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Mat4 ortho = Mat4::ortho(0.0f, static_cast<float>(screen_w_),
static_cast<float>(screen_h_), 0.0f, -1.0f, 1.0f);
ui_shader_.use();
ui_shader_.set_mat4("uOrtho", ortho);
ui_shader_.set_int("uTex", 0);
gl::BindVertexArray(vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, vbo_);
gl::BufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(verts_.size() * sizeof(UiVertex)),
verts_.data(), GL_DYNAMIC_DRAW);
gl::ActiveTexture(GL_TEXTURE0);
for (const auto& b : batches_) {
glBindTexture(GL_TEXTURE_2D, b.tex);
glDrawArrays(GL_TRIANGLES, static_cast<GLint>(b.first), static_cast<GLsizei>(b.count));
}
gl::BindVertexArray(0);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}
void UiRenderer::draw_rect(float x, float y, float w, float h, const Vec4& color) {
push_quad(white_tex_, x, y, x + w, y + h, 0, 0, 1, 1, color);
}
void UiRenderer::draw_rect_outline(float x, float y, float w, float h, float t, const Vec4& color) {
draw_rect(x, y, w, t, color);
draw_rect(x, y + h - t, w, t, color);
draw_rect(x, y + t, t, std::max(0.0f, h - 2 * t), color);
draw_rect(x + w - t, y + t, t, std::max(0.0f, h - 2 * t), color);
}
void UiRenderer::draw_line(float x0, float y0, float x1, float y1, float thickness, const Vec4& color) {
float dx = x1 - x0;
float dy = y1 - y0;
float len = std::sqrt(dx * dx + dy * dy);
if (len < 0.5f) return;
float nx = (-dy / len) * (thickness * 0.5f);
float ny = (dx / len) * (thickness * 0.5f);
uint32_t start = static_cast<uint32_t>(verts_.size());
verts_.push_back({x0 - nx, y0 - ny, 0, 0, color.x, color.y, color.z, color.w});
verts_.push_back({x1 - nx, y1 - ny, 1, 0, color.x, color.y, color.z, color.w});
verts_.push_back({x1 + nx, y1 + ny, 1, 1, color.x, color.y, color.z, color.w});
verts_.push_back({x0 - nx, y0 - ny, 0, 0, color.x, color.y, color.z, color.w});
verts_.push_back({x1 + nx, y1 + ny, 1, 1, color.x, color.y, color.z, color.w});
verts_.push_back({x0 + nx, y0 + ny, 0, 1, color.x, color.y, color.z, color.w});
if (!batches_.empty() && batches_.back().tex == white_tex_) {
batches_.back().count += 6;
} else {
batches_.push_back({white_tex_, start, 6});
}
}
float UiRenderer::measure_text_w(const std::string& text, float scale) const {
if (text.empty()) return 0.0f;
return static_cast<float>(text.size()) * 6.0f * scale - scale;
}
void UiRenderer::draw_text(float x, float y, float scale, const std::string& text,
const Vec4& color, bool shadow) {
if (shadow) {
Vec4 sh(0.0f, 0.0f, 0.0f, color.w * 0.78f);
draw_text(x + scale, y + scale, scale, text, sh, false);
}
float cx = x;
for (char ch : text) {
const Glyph5x7& g = get_glyph(ch);
for (int r = 0; r < 7; ++r) {
uint8_t row = g.rows[r];
if (row == 0) continue;
for (int c = 0; c < 5; ++c) {
if (row & (1u << (4 - c))) {
draw_rect(cx + c * scale, y + r * scale, scale, scale, color);
}
}
}
cx += 6.0f * scale;
}
}
void UiRenderer::draw_text_centered(float cx, float y, float scale, const std::string& text,
const Vec4& color, bool shadow) {
float w = measure_text_w(text, scale);
draw_text(cx - w * 0.5f, y, scale, text, color, shadow);
}
void UiRenderer::draw_screen_cover(const std::string& screen_key, float alpha) {
auto it = screens_.find(screen_key);
if (it == screens_.end() || !it->second.tex) return;
push_quad(it->second.tex, 0, 0, static_cast<float>(screen_w_), static_cast<float>(screen_h_),
0, 0, 1, 1, Vec4(1, 1, 1, alpha));
}
void UiRenderer::draw_screen_4_3(const std::string& screen_key, float alpha) {
auto it = screens_.find(screen_key);
if (it == screens_.end() || !it->second.tex) return;
float target_aspect = 4.0f / 3.0f;
float win_aspect = static_cast<float>(screen_w_) / static_cast<float>(screen_h_);
float w = static_cast<float>(screen_w_);
float h = static_cast<float>(screen_h_);
float x = 0.0f, y = 0.0f;
if (win_aspect > target_aspect) {
w = h * target_aspect;
x = (static_cast<float>(screen_w_) - w) * 0.5f;
} else {
h = w / target_aspect;
y = (static_cast<float>(screen_h_) - h) * 0.5f;
}
push_quad(it->second.tex, x, y, x + w, y + h, 0, 0, 1, 1, Vec4(1, 1, 1, alpha));
}
void UiRenderer::draw_bank_sprite(const std::string& bank_key, int index, float x, float y,
float scale, const Vec4& tint) {
auto it = banks_.find(bank_key);
if (it == banks_.end() || index < 0 || static_cast<size_t>(index) >= it->second.size()) return;
const auto& sp = it->second[index];
if (!sp.tex || sp.width <= 0 || sp.height <= 0) return;
push_quad(sp.tex, x, y, x + sp.width * scale, y + sp.height * scale, 0, 0, 1, 1, tint);
}
bool UiRenderer::get_bank_sprite_size(const std::string& bank_key, int index,
int& out_w, int& out_h) const {
auto it = banks_.find(bank_key);
if (it == banks_.end() || index < 0 || static_cast<size_t>(index) >= it->second.size()) {
return false;
}
out_w = it->second[index].width;
out_h = it->second[index].height;
return out_w > 0 && out_h > 0;
}
void UiRenderer::update_stream_rgba(int w, int h, const uint8_t* rgba) {
if (w <= 0 || h <= 0 || !rgba) return;
if (!stream_tex_ || stream_w_ != w || stream_h_ != h) {
stream_w_ = w;
stream_h_ = h;
upload_rgba(stream_tex_, w, h, rgba, true);
} else {
glBindTexture(GL_TEXTURE_2D, stream_tex_);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba);
}
}
void UiRenderer::draw_stream_4_3() {
if (!stream_tex_) return;
float target_aspect = 4.0f / 3.0f;
float win_aspect = static_cast<float>(screen_w_) / static_cast<float>(screen_h_);
float w = static_cast<float>(screen_w_);
float h = static_cast<float>(screen_h_);
float x = 0.0f, y = 0.0f;
if (win_aspect > target_aspect) {
w = h * target_aspect;
x = (static_cast<float>(screen_w_) - w) * 0.5f;
} else {
h = w / target_aspect;
y = (static_cast<float>(screen_h_) - h) * 0.5f;
}
push_quad(stream_tex_, x, y, x + w, y + h, 0, 0, 1, 1, Vec4(1, 1, 1, 1));
}
} // namespace top_octane::render
+95
View File
@@ -0,0 +1,95 @@
#pragma once
#include "assets/palette.hpp"
#include "assets/sprites.hpp"
#include "core/math.hpp"
#include "core/vfs.hpp"
#include "render/gl_api.hpp"
#include "render/shader.hpp"
#include <string>
#include <unordered_map>
#include <vector>
namespace top_octane::render {
struct GpuSpriteTex {
GLuint tex = 0;
int width = 0;
int height = 0;
};
class UiRenderer {
public:
UiRenderer() = default;
~UiRenderer();
UiRenderer(const UiRenderer&) = delete;
UiRenderer& operator=(const UiRenderer&) = delete;
bool init(const Vfs& vfs, const assets::Palette& pal);
void shutdown();
void begin(int screen_w, int screen_h);
void end();
// Primitives
void draw_rect(float x, float y, float w, float h, const Vec4& color);
void draw_rect_outline(float x, float y, float w, float h, float thickness, const Vec4& color);
void draw_line(float x0, float y0, float x1, float y1, float thickness, const Vec4& color);
// Text rendering (crisp built-in 5x7 font covering full ASCII)
void draw_text(float x, float y, float scale, const std::string& text,
const Vec4& color = Vec4(1, 1, 1, 1), bool shadow = true);
void draw_text_centered(float cx, float y, float scale, const std::string& text,
const Vec4& color = Vec4(1, 1, 1, 1), bool shadow = true);
float measure_text_w(const std::string& text, float scale) const;
// Bullfrog sprite & raw screen helpers
void draw_screen_cover(const std::string& screen_key, float alpha = 1.0f);
void draw_screen_4_3(const std::string& screen_key, float alpha = 1.0f);
void draw_bank_sprite(const std::string& bank_key, int index, float x, float y,
float scale = 1.0f, const Vec4& tint = Vec4(1, 1, 1, 1));
bool get_bank_sprite_size(const std::string& bank_key, int index, int& out_w, int& out_h) const;
// Streaming RGBA texture for Intro FLIC playback
void update_stream_rgba(int w, int h, const uint8_t* rgba);
void draw_stream_4_3();
private:
struct UiVertex {
float x, y;
float u, v;
float r, g, b, a;
};
struct DrawBatch {
GLuint tex = 0;
uint32_t first = 0;
uint32_t count = 0;
};
void upload_rgba(GLuint& tex, int w, int h, const uint8_t* rgba, bool linear);
void push_quad(GLuint tex, float x0, float y0, float x1, float y1,
float u0, float v0, float u1, float v1, const Vec4& c);
void load_bank(const Vfs& vfs, const assets::Palette& pal,
const std::string& key, const std::string& stem);
bool initialized_ = false;
ShaderProgram ui_shader_;
GLuint vao_ = 0, vbo_ = 0;
GLuint white_tex_ = 0;
GLuint stream_tex_ = 0;
int stream_w_ = 0, stream_h_ = 0;
int screen_w_ = 1280;
int screen_h_ = 720;
std::unordered_map<std::string, GpuSpriteTex> screens_;
std::unordered_map<std::string, std::vector<GpuSpriteTex>> banks_;
std::vector<UiVertex> verts_;
std::vector<DrawBatch> batches_;
};
} // namespace top_octane::render
+256
View File
@@ -0,0 +1,256 @@
#include "render/world_geometry.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::render {
namespace {
inline float norm_light(uint16_t ill) {
// 8192 is neutral brightness in Bullfrog MapEntry
return std::clamp(static_cast<float>(ill) / 8192.0f, 0.30f, 1.45f);
}
inline Vec3 vertex_normal(const assets::LevelData& level, int x, int z) {
float hL = level.cell_height_world(x - 1, z);
float hR = level.cell_height_world(x + 1, z);
float hD = level.cell_height_world(x, z - 1);
float hU = level.cell_height_world(x, z + 1);
return Vec3(hL - hR, 2.0f, hD - hU).normalized();
}
inline void dihedral_uvs(uint8_t mod, float out_u[4], float out_v[4]) {
// Base UVs for TL(0,0), TR(1,0), BR(1,1), BL(0,1)
static constexpr float base_u[4] = {0.0f, 1.0f, 1.0f, 0.0f};
static constexpr float base_v[4] = {0.0f, 0.0f, 1.0f, 1.0f};
for (int i = 0; i < 4; ++i) {
float u = base_u[i];
float v = base_v[i];
if (mod & 1u) u = 1.0f - u;
if (mod & 2u) v = 1.0f - v;
if (mod & 4u) std::swap(u, v);
out_u[i] = u;
out_v[i] = v;
}
}
void build_cell_quad(const assets::LevelData& level, int x, int z, WorldVertex out[4]) {
const assets::MapEntry& m = level.cell(x, z);
int floor_tile = 0;
if (m.tex_or_col >= 0) {
floor_tile = std::clamp<int>(m.tex_or_col, 0, 255);
} else {
int cidx = -m.tex_or_col;
if (cidx > 0 && cidx < assets::kMaxColumns) {
floor_tile = std::clamp<int>(level.columns[cidx].floor_tex, 0, 255);
}
}
float u[4], v[4];
dihedral_uvs(static_cast<uint8_t>((m.flags >> 4) & 7u), u, v);
const int cx[4] = {x, x + 1, x + 1, x};
const int cz[4] = {z, z, z + 1, z + 1};
for (int k = 0; k < 4; ++k) {
const assets::MapEntry& vm = level.cell(cx[k], cz[k]);
out[k].pos = Vec3(static_cast<float>(cx[k]), level.cell_height_world(cx[k], cz[k]),
static_cast<float>(cz[k]));
out[k].normal = vertex_normal(level, cx[k], cz[k]);
out[k].u = u[k];
out[k].v = v[k];
out[k].tile = static_cast<float>(floor_tile);
out[k].light = norm_light(vm.illumination);
}
}
bool has_block_at(const assets::LevelData& level, int x, int z, int slot) {
if (x < 0 || x >= assets::kMapWidth || z < 0 || z >= assets::kMapHeight || slot < 0 || slot >= 8) {
return false;
}
const assets::MapEntry& m = level.cell(x, z);
if (m.tex_or_col >= 0) return false;
int cidx = -m.tex_or_col;
if (cidx <= 0 || cidx >= assets::kMaxColumns) return false;
return (level.columns[cidx].shape_mask & (1u << slot)) != 0;
}
void emit_quad(std::vector<WorldVertex>& verts, std::vector<uint32_t>& indices,
const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec3& p3,
const Vec3& normal, uint8_t tex_id, uint8_t uv_mod, float light) {
float u[4], v[4];
dihedral_uvs(uv_mod, u, v);
uint32_t base = static_cast<uint32_t>(verts.size());
float tile = static_cast<float>(tex_id);
verts.push_back({p0, normal, u[0], v[0], tile, light});
verts.push_back({p1, normal, u[1], v[1], tile, light});
verts.push_back({p2, normal, u[2], v[2], tile, light});
verts.push_back({p3, normal, u[3], v[3], tile, light});
// Counter-clockwise outward-facing winding matching declared normal
indices.push_back(base + 0);
indices.push_back(base + 3);
indices.push_back(base + 2);
indices.push_back(base + 0);
indices.push_back(base + 2);
indices.push_back(base + 1);
}
} // namespace
WorldGeometry build_level_geometry(const assets::LevelData& level) {
WorldGeometry geo;
const int gw = assets::kMapWidth - 1;
const int gh = assets::kMapHeight - 1;
const size_t cell_count = static_cast<size_t>(gw) * static_cast<size_t>(gh);
geo.terrain_verts.resize(cell_count * 4u);
geo.terrain_indices.reserve(cell_count * 6u);
for (int z = 0; z < gh; ++z) {
for (int x = 0; x < gw; ++x) {
size_t cidx = static_cast<size_t>(z) * gw + x;
uint32_t base = static_cast<uint32_t>(cidx * 4u);
build_cell_quad(level, x, z, &geo.terrain_verts[base]);
// Counter-clockwise upward-facing winding (+Y normal)
geo.terrain_indices.push_back(base + 0);
geo.terrain_indices.push_back(base + 3);
geo.terrain_indices.push_back(base + 2);
geo.terrain_indices.push_back(base + 0);
geo.terrain_indices.push_back(base + 2);
geo.terrain_indices.push_back(base + 1);
}
}
// 3D Column Blocks
for (int z = 0; z < assets::kMapHeight; ++z) {
for (int x = 0; x < assets::kMapWidth; ++x) {
const assets::MapEntry& m = level.cell(x, z);
if (m.tex_or_col >= 0) continue;
int col_idx = -m.tex_or_col;
if (col_idx <= 0 || col_idx >= assets::kMaxColumns) continue;
const assets::ColumnDefinition& col = level.columns[col_idx];
if (col.shape_mask == 0) continue;
float h00 = level.cell_height_world(x, z);
float h10 = level.cell_height_world(x + 1, z);
float h01 = level.cell_height_world(x, z + 1);
float h11 = level.cell_height_world(x + 1, z + 1);
float lgt = norm_light(m.illumination);
float fx = static_cast<float>(x);
float fz = static_cast<float>(z);
for (int slot = 0; slot < 8; ++slot) {
if ((col.shape_mask & (1u << slot)) == 0) continue;
int blk_id = col.blocks[slot];
if (blk_id < 0 || blk_id >= assets::kMaxBlocks) continue;
const assets::BlockDefinition& blk = level.blocks[blk_id];
float sf = static_cast<float>(slot);
float b00 = h00 + sf, b10 = h10 + sf, b01 = h01 + sf, b11 = h11 + sf;
float t00 = b00 + 1.0f, t10 = b10 + 1.0f, t01 = b01 + 1.0f, t11 = b11 + 1.0f;
// 0: North (-Z)
if (!has_block_at(level, x, z - 1, slot)) {
emit_quad(geo.column_verts, geo.column_indices,
Vec3(fx + 1, t10, fz), Vec3(fx, t00, fz),
Vec3(fx, b00, fz), Vec3(fx + 1, b10, fz),
Vec3(0, 0, -1), blk.tex[0], blk.attrs[0] & 7u, lgt * 0.90f);
}
// 1: East (+X)
if (!has_block_at(level, x + 1, z, slot)) {
emit_quad(geo.column_verts, geo.column_indices,
Vec3(fx + 1, t11, fz + 1), Vec3(fx + 1, t10, fz),
Vec3(fx + 1, b10, fz), Vec3(fx + 1, b11, fz + 1),
Vec3(1, 0, 0), blk.tex[1], blk.attrs[1] & 7u, lgt * 0.85f);
}
// 2: South (+Z)
if (!has_block_at(level, x, z + 1, slot)) {
emit_quad(geo.column_verts, geo.column_indices,
Vec3(fx, t01, fz + 1), Vec3(fx + 1, t11, fz + 1),
Vec3(fx + 1, b11, fz + 1), Vec3(fx, b01, fz + 1),
Vec3(0, 0, 1), blk.tex[2], blk.attrs[2] & 7u, lgt * 0.95f);
}
// 3: West (-X)
if (!has_block_at(level, x - 1, z, slot)) {
emit_quad(geo.column_verts, geo.column_indices,
Vec3(fx, t00, fz), Vec3(fx, t01, fz + 1),
Vec3(fx, b01, fz + 1), Vec3(fx, b00, fz),
Vec3(-1, 0, 0), blk.tex[3], blk.attrs[3] & 7u, lgt * 0.80f);
}
// 4: Top (+Y)
if (!has_block_at(level, x, z, slot + 1)) {
Vec3 p0(fx, t00, fz), p1(fx + 1, t10, fz);
Vec3 p2(fx + 1, t11, fz + 1), p3(fx, t01, fz + 1);
Vec3 top_n = (p3 - p0).cross(p2 - p0) + (p2 - p0).cross(p1 - p0);
top_n = (top_n.len_sq() > 1e-6f) ? top_n.normalized() : Vec3(0, 1, 0);
emit_quad(geo.column_verts, geo.column_indices,
p0, p1, p2, p3,
top_n, blk.tex[4], blk.attrs[4] & 7u, lgt * 1.05f);
}
// 5: Bottom (-Y) - needed for elevated overpass/gantry blocks
if (slot > 0 && !has_block_at(level, x, z, slot - 1)) {
Vec3 p0(fx, b01, fz + 1), p1(fx + 1, b11, fz + 1);
Vec3 p2(fx + 1, b10, fz), p3(fx, b00, fz);
Vec3 bot_n = (p3 - p0).cross(p2 - p0) + (p2 - p0).cross(p1 - p0);
bot_n = (bot_n.len_sq() > 1e-6f) ? bot_n.normalized() : Vec3(0, -1, 0);
emit_quad(geo.column_verts, geo.column_indices,
p0, p1, p2, p3,
bot_n, blk.tex[5], blk.attrs[5] & 7u, lgt * 0.70f);
}
}
}
}
return geo;
}
void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x1, int z1,
std::vector<WorldVertex>& terrain_verts) {
const int gw = assets::kMapWidth - 1;
const int gh = assets::kMapHeight - 1;
x0 = std::clamp(x0, 0, gw - 1);
z0 = std::clamp(z0, 0, gh - 1);
x1 = std::clamp(x1, 0, gw - 1);
z1 = std::clamp(z1, 0, gh - 1);
if (terrain_verts.size() < static_cast<size_t>(gw) * gh * 4u) return;
for (int z = z0; z <= z1; ++z) {
for (int x = x0; x <= x1; ++x) {
size_t base = (static_cast<size_t>(z) * gw + x) * 4u;
build_cell_quad(level, x, z, &terrain_verts[base]);
}
}
}
ModelGeometry build_model_geometry(const assets::ModelMesh& mesh, const assets::Palette& pal) {
ModelGeometry out;
out.verts.reserve(mesh.triangles.size() * 3u);
out.indices.reserve(mesh.triangles.size() * 3u);
for (const auto& tri : mesh.triangles) {
const Vec3& p0 = mesh.vertices[tri.v[0]].pos;
const Vec3& p1 = mesh.vertices[tri.v[1]].pos;
const Vec3& p2 = mesh.vertices[tri.v[2]].pos;
Vec3 n = (p1 - p0).cross(p2 - p0).normalized();
if (n.len_sq() < 0.001f) n = Vec3(0, 1, 0);
Vec4 col(1.0f, 1.0f, 1.0f, 1.0f);
if (!tri.textured) {
const assets::Rgba8& pc = pal.colors[tri.pal_color];
col = Vec4(pc.r / 255.0f, pc.g / 255.0f, pc.b / 255.0f, 1.0f);
}
uint32_t base = static_cast<uint32_t>(out.verts.size());
for (int k = 0; k < 3; ++k) {
const auto& mv = mesh.vertices[tri.v[k]];
float s = std::clamp(0.65f + (mv.shade / 128.0f) * 0.45f, 0.5f, 1.25f);
out.verts.push_back({mv.pos, n, tri.u[k], tri.v_coord[k], col,
tri.textured ? 1.0f : 0.0f, s});
out.indices.push_back(base + static_cast<uint32_t>(k));
}
}
return out;
}
} // namespace top_octane::render
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "assets/level.hpp"
#include "assets/model.hpp"
#include "assets/palette.hpp"
#include "core/math.hpp"
#include <cstdint>
#include <vector>
namespace top_octane::render {
struct WorldVertex {
Vec3 pos;
Vec3 normal;
float u = 0.0f;
float v = 0.0f;
float tile = 0.0f;
float light = 1.0f;
};
struct ModelGpuVertex {
Vec3 pos;
Vec3 normal;
float u = 0.0f;
float v = 0.0f;
Vec4 color{1.0f, 1.0f, 1.0f, 1.0f}; // white for textured faces, palette RGBA for untextured faces
float textured = 1.0f;
float shade = 1.0f;
};
struct WorldGeometry {
std::vector<WorldVertex> terrain_verts;
std::vector<uint32_t> terrain_indices;
std::vector<WorldVertex> column_verts;
std::vector<uint32_t> column_indices;
};
struct ModelGeometry {
std::vector<ModelGpuVertex> verts;
std::vector<uint32_t> indices;
};
// Builds full terrain & column meshes for a level (pure CPU, headless testable)
WorldGeometry build_level_geometry(const assets::LevelData& level);
// Rebuilds just a rectangular cell range [x0..x1] x [z0..z1] into terrain_verts (for live morphs)
void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x1, int z1,
std::vector<WorldVertex>& terrain_verts);
// Converts a Bullfrog 3D ModelMesh into GPU-ready triangles with face normals
ModelGeometry build_model_geometry(const assets::ModelMesh& mesh, const assets::Palette& pal);
} // namespace top_octane::render
+890
View File
@@ -0,0 +1,890 @@
#include "render/world_renderer.hpp"
#include "core/log.hpp"
#include <algorithm>
#include <cmath>
#include <cstddef>
namespace top_octane::render {
namespace {
constexpr const char* kWorldVS = R"glsl(
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aUv;
layout(location = 3) in float aTile;
layout(location = 4) in float aLight;
uniform mat4 uViewProj;
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out float vTile;
out float vLight;
void main() {
vWorldPos = aPos;
vNormal = aNormal;
vUv = aUv;
vTile = aTile;
vLight = aLight;
gl_Position = uViewProj * vec4(aPos, 1.0);
}
)glsl";
constexpr const char* kWorldFS = R"glsl(
#version 330 core
in vec3 vWorldPos;
in vec3 vNormal;
in vec2 vUv;
in float vTile;
in float vLight;
uniform sampler2DArray uTexArray;
uniform vec3 uCamPos;
uniform vec3 uFogColor;
uniform float uDrawDist;
out vec4 FragColor;
void main() {
vec4 texel = texture(uTexArray, vec3(vUv, floor(vTile + 0.5)));
vec3 sunDir = normalize(vec3(0.45, 0.80, 0.38));
float ndl = clamp(dot(normalize(vNormal), sunDir), 0.0, 1.0);
float shade = vLight * (0.72 + 0.35 * ndl);
vec3 lit = texel.rgb * shade;
float dist = length(vWorldPos - uCamPos);
float fogStart = uDrawDist * 0.45;
float fogFactor = clamp((dist - fogStart) / max(uDrawDist - fogStart, 1.0), 0.0, 1.0);
vec3 finalRgb = mix(lit, uFogColor, fogFactor * fogFactor);
FragColor = vec4(clamp(finalRgb, 0.0, 1.0), 1.0);
}
)glsl";
constexpr const char* kModelVS = R"glsl(
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aUv;
layout(location = 3) in vec4 aColor;
layout(location = 4) in float aTextured;
layout(location = 5) in float aShade;
uniform mat4 uModel;
uniform mat4 uViewProj;
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out vec4 vColor;
out float vTextured;
out float vShade;
void main() {
vec4 wp = uModel * vec4(aPos, 1.0);
vWorldPos = wp.xyz;
vNormal = mat3(uModel) * aNormal;
vUv = aUv;
vColor = aColor;
vTextured = aTextured;
vShade = aShade;
gl_Position = uViewProj * wp;
}
)glsl";
constexpr const char* kModelFS = R"glsl(
#version 330 core
in vec3 vWorldPos;
in vec3 vNormal;
in vec2 vUv;
in vec4 vColor;
in float vTextured;
in float vShade;
uniform sampler2D uAtlas;
uniform vec4 uTint;
uniform vec3 uCamPos;
uniform vec3 uFogColor;
uniform float uDrawDist;
uniform float uEnableFog;
out vec4 FragColor;
void main() {
vec4 base = vColor;
if (vTextured > 0.5) {
vec4 t = texture(uAtlas, vUv);
if (t.a < 0.1) discard;
base = t;
}
vec3 sunDir = normalize(vec3(0.45, 0.80, 0.38));
float ndl = abs(dot(normalize(vNormal), sunDir));
float shade = vShade * (0.68 + 0.42 * ndl);
vec3 rgb = base.rgb * shade * uTint.rgb;
if (uEnableFog > 0.5) {
float dist = length(vWorldPos - uCamPos);
float fogStart = uDrawDist * 0.45;
float fogFactor = clamp((dist - fogStart) / max(uDrawDist - fogStart, 1.0), 0.0, 1.0);
rgb = mix(rgb, uFogColor, fogFactor * fogFactor);
}
FragColor = vec4(clamp(rgb, 0.0, 1.0), base.a * uTint.a);
}
)glsl";
constexpr const char* kSkyVS = R"glsl(
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aUv;
uniform mat4 uViewProjNoTrans;
out vec2 vUv;
void main() {
vUv = aUv;
vec4 p = uViewProjNoTrans * vec4(aPos, 1.0);
gl_Position = p.xyww;
}
)glsl";
constexpr const char* kSkyFS = R"glsl(
#version 330 core
in vec2 vUv;
uniform sampler2D uSkyTex;
uniform vec3 uFogColor;
out vec4 FragColor;
void main() {
vec3 sky = texture(uSkyTex, vUv).rgb;
// Preserve clouds/mountains (v = 0.59..0.91) and blend smoothly into fog at the horizon
float hBlend = smoothstep(0.91, 0.968, vUv.y);
FragColor = vec4(mix(sky, uFogColor, hBlend), 1.0);
}
)glsl";
constexpr const char* kParticleVS = R"glsl(
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec2 aUv;
layout(location = 2) in vec4 aColor;
uniform mat4 uViewProj;
out vec2 vUv;
out vec4 vColor;
void main() {
vUv = aUv;
vColor = aColor;
gl_Position = uViewProj * vec4(aPos, 1.0);
}
)glsl";
constexpr const char* kParticleFS = R"glsl(
#version 330 core
in vec2 vUv;
in vec4 vColor;
out vec4 FragColor;
void main() {
vec2 d = vUv * 2.0 - 1.0;
float r = dot(d, d);
if (r > 1.0) discard;
float alpha = (1.0 - r) * vColor.a;
FragColor = vec4(vColor.rgb, alpha);
}
)glsl";
constexpr const char* kClassicVS = R"glsl(
#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec2 aUv;
out vec2 vUv;
void main() {
vUv = aUv;
gl_Position = vec4(aPos, 0.0, 1.0);
}
)glsl";
constexpr const char* kClassicFS = R"glsl(
#version 330 core
in vec2 vUv;
uniform sampler2D uSceneTex;
uniform sampler2D uPaletteTex;
uniform float uScanlines;
uniform float uHeightPx;
out vec4 FragColor;
void main() {
vec3 col = texture(uSceneTex, vUv).rgb;
vec3 best = col;
float bestDist = 1e9;
// Quantize against authentic 256-color PALET0-0.DAT lookup texture
for (int i = 1; i < 256; ++i) {
vec3 p = texelFetch(uPaletteTex, ivec2(i, 0), 0).rgb;
vec3 d = col - p;
float d2 = dot(d, d);
if (d2 < bestDist) {
bestDist = d2;
best = p;
}
}
if (uScanlines > 0.5) {
float row = mod(floor(vUv.y * uHeightPx), 2.0);
if (row < 0.5) best *= 0.80;
}
FragColor = vec4(best, 1.0);
}
)glsl";
void set_world_vertex_attribs() {
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(WorldVertex),
reinterpret_cast<void*>(offsetof(WorldVertex, pos)));
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(WorldVertex),
reinterpret_cast<void*>(offsetof(WorldVertex, normal)));
gl::EnableVertexAttribArray(2);
gl::VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(WorldVertex),
reinterpret_cast<void*>(offsetof(WorldVertex, u)));
gl::EnableVertexAttribArray(3);
gl::VertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(WorldVertex),
reinterpret_cast<void*>(offsetof(WorldVertex, tile)));
gl::EnableVertexAttribArray(4);
gl::VertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, sizeof(WorldVertex),
reinterpret_cast<void*>(offsetof(WorldVertex, light)));
}
} // namespace
WorldRenderer::~WorldRenderer() {
shutdown();
}
bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) {
if (initialized_) return true;
if (!gl::is_loaded()) {
LOG_ERROR("GL API not initialized before WorldRenderer::init");
return false;
}
if (!world_shader_.build(kWorldVS, kWorldFS, "world") ||
!model_shader_.build(kModelVS, kModelFS, "model") ||
!sky_shader_.build(kSkyVS, kSkyFS, "sky") ||
!particle_shader_.build(kParticleVS, kParticleFS, "particle") ||
!classic_shader_.build(kClassicVS, kClassicFS, "classic")) {
return false;
}
if (!obj_atlas_.load(vfs, pal)) {
return false;
}
// Upload object atlas texture (256 x 768)
glGenTextures(1, &tex_obj_atlas_);
glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, obj_atlas_.width, obj_atlas_.height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, obj_atlas_.rgba.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Upload 256 x 1 palette texture for Classic Mode quantization
uint8_t pal_rgba[256 * 4];
for (int i = 0; i < 256; ++i) {
pal_rgba[i * 4 + 0] = pal.colors[i].r;
pal_rgba[i * 4 + 1] = pal.colors[i].g;
pal_rgba[i * 4 + 2] = pal.colors[i].b;
pal_rgba[i * 4 + 3] = 255;
}
glGenTextures(1, &tex_palette_);
glBindTexture(GL_TEXTURE_2D, tex_palette_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pal_rgba);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Build cylindrical skybox mesh with zenith and nadir caps
constexpr int kSegs = 32;
constexpr float kSkyVTop = 112.0f / 256.0f; // 0.4375: true zenith row in SKY0-x
constexpr float kSkyVBot = 248.0f / 256.0f; // 0.96875: true horizon row in SKY0-x
std::vector<float> sky_verts;
sky_verts.reserve(kSegs * 12 * 5);
for (int i = 0; i < kSegs; ++i) {
float a0 = kTwoPi * static_cast<float>(i) / kSegs;
float a1 = kTwoPi * static_cast<float>(i + 1) / kSegs;
float u0 = static_cast<float>(i) / kSegs * 2.0f; // wraps twice around horizon
float u1 = static_cast<float>(i + 1) / kSegs * 2.0f;
float u_mid = 0.5f * (u0 + u1);
float r = 20.0f;
float x0 = std::cos(a0) * r, z0 = std::sin(a0) * r;
float x1 = std::cos(a1) * r, z1 = std::sin(a1) * r;
float y_top = 18.0f, y_bot = -2.0f;
auto push = [&](float x, float y, float z, float u, float v) {
sky_verts.push_back(x);
sky_verts.push_back(y);
sky_verts.push_back(z);
sky_verts.push_back(u);
sky_verts.push_back(v);
};
// Side wall
push(x0, y_top, z0, u0, kSkyVTop);
push(x0, y_bot, z0, u0, kSkyVBot);
push(x1, y_bot, z1, u1, kSkyVBot);
push(x0, y_top, z0, u0, kSkyVTop);
push(x1, y_bot, z1, u1, kSkyVBot);
push(x1, y_top, z1, u1, kSkyVTop);
// Zenith cap
push(0.0f, y_top, 0.0f, u_mid, kSkyVTop);
push(x0, y_top, z0, u0, kSkyVTop);
push(x1, y_top, z1, u1, kSkyVTop);
// Nadir cap
push(0.0f, y_bot, 0.0f, u_mid, kSkyVBot);
push(x1, y_bot, z1, u1, kSkyVBot);
push(x0, y_bot, z0, u0, kSkyVBot);
}
sky_vert_count_ = static_cast<GLsizei>(sky_verts.size() / 5);
gl::GenVertexArrays(1, &sky_vao_);
gl::GenBuffers(1, &sky_vbo_);
gl::BindVertexArray(sky_vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, sky_vbo_);
gl::BufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(sky_verts.size() * sizeof(float)),
sky_verts.data(), GL_STATIC_DRAW);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), nullptr);
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float),
reinterpret_cast<void*>(3 * sizeof(float)));
// Fullscreen quad for Classic FBO blit
static constexpr float kQuadVerts[] = {
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
};
gl::GenVertexArrays(1, &quad_vao_);
gl::GenBuffers(1, &quad_vbo_);
gl::BindVertexArray(quad_vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, quad_vbo_);
gl::BufferData(GL_ARRAY_BUFFER, sizeof(kQuadVerts), kQuadVerts, GL_STATIC_DRAW);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
reinterpret_cast<void*>(2 * sizeof(float)));
// Dynamic particle stream VAO/VBO
gl::GenVertexArrays(1, &part_vao_);
gl::GenBuffers(1, &part_vbo_);
gl::BindVertexArray(part_vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, part_vbo_);
gl::BufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), nullptr);
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float),
reinterpret_cast<void*>(3 * sizeof(float)));
gl::EnableVertexAttribArray(2);
gl::VertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float),
reinterpret_cast<void*>(5 * sizeof(float)));
gl::BindVertexArray(0);
initialized_ = true;
return true;
}
void WorldRenderer::shutdown() {
if (!initialized_) return;
destroy_mesh(terrain_mesh_);
destroy_mesh(column_mesh_);
for (auto& [k, m] : model_cache_) {
destroy_mesh(m);
}
model_cache_.clear();
if (gl::is_loaded()) {
if (sky_vao_) gl::DeleteVertexArrays(1, &sky_vao_);
if (sky_vbo_) gl::DeleteBuffers(1, &sky_vbo_);
if (quad_vao_) gl::DeleteVertexArrays(1, &quad_vao_);
if (quad_vbo_) gl::DeleteBuffers(1, &quad_vbo_);
if (part_vao_) gl::DeleteVertexArrays(1, &part_vao_);
if (part_vbo_) gl::DeleteBuffers(1, &part_vbo_);
if (classic_fbo_) gl::DeleteFramebuffers(1, &classic_fbo_);
if (classic_depth_rbo_) gl::DeleteRenderbuffers(1, &classic_depth_rbo_);
}
if (tex_terrain_array_) glDeleteTextures(1, &tex_terrain_array_);
if (tex_sky_) glDeleteTextures(1, &tex_sky_);
if (tex_obj_atlas_) glDeleteTextures(1, &tex_obj_atlas_);
if (tex_palette_) glDeleteTextures(1, &tex_palette_);
if (classic_color_tex_) glDeleteTextures(1, &classic_color_tex_);
sky_vao_ = sky_vbo_ = quad_vao_ = quad_vbo_ = part_vao_ = part_vbo_ = 0;
classic_fbo_ = classic_depth_rbo_ = classic_color_tex_ = 0;
tex_terrain_array_ = tex_sky_ = tex_obj_atlas_ = tex_palette_ = 0;
classic_w_ = classic_h_ = 0;
world_shader_.destroy();
model_shader_.destroy();
sky_shader_.destroy();
particle_shader_.destroy();
classic_shader_.destroy();
initialized_ = false;
}
void WorldRenderer::destroy_mesh(GpuMesh& m) {
if (gl::is_loaded()) {
if (m.vao) gl::DeleteVertexArrays(1, &m.vao);
if (m.vbo) gl::DeleteBuffers(1, &m.vbo);
if (m.ebo) gl::DeleteBuffers(1, &m.ebo);
}
m = GpuMesh{};
}
void WorldRenderer::upload_world_mesh(GpuMesh& m, const std::vector<WorldVertex>& verts,
const std::vector<uint32_t>& indices, bool dynamic) {
destroy_mesh(m);
if (verts.empty() || indices.empty()) return;
gl::GenVertexArrays(1, &m.vao);
gl::GenBuffers(1, &m.vbo);
gl::GenBuffers(1, &m.ebo);
gl::BindVertexArray(m.vao);
gl::BindBuffer(GL_ARRAY_BUFFER, m.vbo);
gl::BufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(verts.size() * sizeof(WorldVertex)),
verts.data(), dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, m.ebo);
gl::BufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(indices.size() * sizeof(uint32_t)),
indices.data(), GL_STATIC_DRAW);
set_world_vertex_attribs();
gl::BindVertexArray(0);
m.index_count = static_cast<GLsizei>(indices.size());
}
bool WorldRenderer::load_level(const Vfs& vfs, const assets::LevelData& level,
const assets::Palette& pal) {
if (!initialized_) return false;
if (!color_tables_.load(vfs, level.world_index, pal) ||
!world_textures_.load(vfs, level.world_index, pal)) {
return false;
}
fog_color_ = color_tables_.fog_color;
// Upload 256 x 64 x 64 terrain texture array
if (tex_terrain_array_) glDeleteTextures(1, &tex_terrain_array_);
glGenTextures(1, &tex_terrain_array_);
glBindTexture(GL_TEXTURE_2D_ARRAY, tex_terrain_array_);
gl::TexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8,
assets::WorldTextures::kTileSize,
assets::WorldTextures::kTileSize,
assets::WorldTextures::kTileCount,
0, GL_RGBA, GL_UNSIGNED_BYTE, world_textures_.tile_rgba.data());
gl::GenerateMipmap(GL_TEXTURE_2D_ARRAY);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Upload 256 x 256 skybox texture
if (tex_sky_) glDeleteTextures(1, &tex_sky_);
glGenTextures(1, &tex_sky_);
glBindTexture(GL_TEXTURE_2D, tex_sky_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
assets::WorldTextures::kSkySize, assets::WorldTextures::kSkySize,
0, GL_RGBA, GL_UNSIGNED_BYTE, world_textures_.sky_rgba.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
apply_texture_filtering(active_filter_);
world_geo_ = build_level_geometry(level);
upload_world_mesh(terrain_mesh_, world_geo_.terrain_verts, world_geo_.terrain_indices, true);
upload_world_mesh(column_mesh_, world_geo_.column_verts, world_geo_.column_indices, false);
LOG_INFO("Loaded level %d GPU geometry: terrain_tris=%d, column_tris=%d",
level.level_number, terrain_mesh_.index_count / 3, column_mesh_.index_count / 3);
return true;
}
void WorldRenderer::update_terrain_region(const assets::LevelData& level,
int x0, int z0, int x1, int z1) {
render::update_terrain_region(level, x0, z0, x1, z1, world_geo_.terrain_verts);
if (!terrain_mesh_.vbo) return;
const int gw = assets::kMapWidth - 1;
const int gh = assets::kMapHeight - 1;
x0 = std::clamp(x0, 0, gw - 1);
z0 = std::clamp(z0, 0, gh - 1);
x1 = std::clamp(x1, 0, gw - 1);
z1 = std::clamp(z1, 0, gh - 1);
gl::BindBuffer(GL_ARRAY_BUFFER, terrain_mesh_.vbo);
for (int z = z0; z <= z1; ++z) {
size_t first_vert = (static_cast<size_t>(z) * gw + x0) * 4u;
size_t num_verts = static_cast<size_t>(x1 - x0 + 1) * 4u;
gl::BufferSubData(GL_ARRAY_BUFFER,
static_cast<GLintptr>(first_vert * sizeof(WorldVertex)),
static_cast<GLsizeiptr>(num_verts * sizeof(WorldVertex)),
&world_geo_.terrain_verts[first_vert]);
}
gl::BindBuffer(GL_ARRAY_BUFFER, 0);
}
bool WorldRenderer::ensure_model(const Vfs& vfs, const std::string& key, const assets::Palette& pal) {
if (model_cache_.count(key)) return true;
assets::ModelMesh mesh;
if (!mesh.load(vfs, "OBJECTS/DATA/" + key + ".DAT", &obj_atlas_)) {
return false;
}
ModelGeometry geo = build_model_geometry(mesh, pal);
if (geo.verts.empty() || geo.indices.empty()) return false;
GpuMesh gpu;
gl::GenVertexArrays(1, &gpu.vao);
gl::GenBuffers(1, &gpu.vbo);
gl::GenBuffers(1, &gpu.ebo);
gl::BindVertexArray(gpu.vao);
gl::BindBuffer(GL_ARRAY_BUFFER, gpu.vbo);
gl::BufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(geo.verts.size() * sizeof(ModelGpuVertex)),
geo.verts.data(), GL_STATIC_DRAW);
gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpu.ebo);
gl::BufferData(GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr>(geo.indices.size() * sizeof(uint32_t)),
geo.indices.data(), GL_STATIC_DRAW);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, pos)));
gl::EnableVertexAttribArray(1);
gl::VertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, normal)));
gl::EnableVertexAttribArray(2);
gl::VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, u)));
gl::EnableVertexAttribArray(3);
gl::VertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, color)));
gl::EnableVertexAttribArray(4);
gl::VertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, textured)));
gl::EnableVertexAttribArray(5);
gl::VertexAttribPointer(5, 1, GL_FLOAT, GL_FALSE, sizeof(ModelGpuVertex),
reinterpret_cast<void*>(offsetof(ModelGpuVertex, shade)));
gl::BindVertexArray(0);
gpu.index_count = static_cast<GLsizei>(geo.indices.size());
model_cache_[key] = gpu;
return true;
}
void WorldRenderer::ensure_classic_fbo(int w, int h) {
if (classic_fbo_ != 0 && classic_w_ == w && classic_h_ == h) return;
if (classic_fbo_) gl::DeleteFramebuffers(1, &classic_fbo_);
if (classic_depth_rbo_) gl::DeleteRenderbuffers(1, &classic_depth_rbo_);
if (classic_color_tex_) glDeleteTextures(1, &classic_color_tex_);
classic_w_ = w;
classic_h_ = h;
glGenTextures(1, &classic_color_tex_);
glBindTexture(GL_TEXTURE_2D, classic_color_tex_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl::GenRenderbuffers(1, &classic_depth_rbo_);
gl::BindRenderbuffer(GL_RENDERBUFFER, classic_depth_rbo_);
gl::RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
gl::GenFramebuffers(1, &classic_fbo_);
gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_);
gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, classic_color_tex_, 0);
gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, classic_depth_rbo_);
gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
}
void WorldRenderer::apply_texture_filtering(TextureFilterMode mode) {
active_filter_ = mode;
GLint min_f = (mode == TextureFilterMode::Linear) ? GL_LINEAR_MIPMAP_LINEAR : GL_NEAREST_MIPMAP_NEAREST;
GLint mag_f = (mode == TextureFilterMode::Linear) ? GL_LINEAR : GL_NEAREST;
if (tex_terrain_array_) {
glBindTexture(GL_TEXTURE_2D_ARRAY, tex_terrain_array_);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, min_f);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, mag_f);
}
if (tex_sky_) {
glBindTexture(GL_TEXTURE_2D, tex_sky_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mag_f);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_f);
}
if (tex_obj_atlas_) {
glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mag_f);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_f);
}
}
void WorldRenderer::begin_frame(int backbuffer_w, int backbuffer_h, const GameConfig& cfg) {
backbuffer_w_ = std::max(backbuffer_w, 1);
backbuffer_h_ = std::max(backbuffer_h, 1);
TextureFilterMode desired = cfg.classic_mode ? TextureFilterMode::Nearest : cfg.texture_filter;
if (desired != active_filter_) {
apply_texture_filtering(desired);
}
if (cfg.classic_mode) {
int cw = cfg.classic_hires ? 640 : 320;
int ch = cfg.classic_hires ? 480 : 200;
ensure_classic_fbo(cw, ch);
gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_);
glViewport(0, 0, cw, ch);
} else {
gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, backbuffer_w_, backbuffer_h_);
}
glClearColor(fog_color_.x, fog_color_.y, fog_color_.z, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector<ModelInstance>& models,
const std::vector<ParticleQuad>& particles,
int viewport_index, int split_count, const GameConfig& cfg) {
int target_w = cfg.classic_mode ? classic_w_ : backbuffer_w_;
int target_h = cfg.classic_mode ? classic_h_ : backbuffer_h_;
if (cfg.classic_mode) {
gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_);
} else {
gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
}
// Compute exact viewport rectangle (for 2P split screen, top=P1, bottom=P2)
int vx = 0, vy = 0, vw = target_w, vh = target_h;
if (split_count == 2) {
vh = target_h / 2;
vy = (viewport_index == 0) ? (target_h - vh) : 0;
}
glViewport(vx, vy, vw, vh);
float aspect = static_cast<float>(vw) / static_cast<float>(std::max(vh, 1));
float fov = cfg.classic_mode ? 62.0f : cfg.fov_deg;
if (split_count == 2) {
// Hor+ adjustment for wide split viewports
aspect = std::max(aspect, 1.0f);
}
float draw_dist = cfg.classic_mode ? 38.0f : cfg.draw_distance;
Mat4 proj = Mat4::perspective(deg_to_rad(fov), aspect, cam.z_near, std::max(cam.z_far, draw_dist + 40.0f));
Mat4 view = Mat4::look_at(cam.eye, cam.target, cam.up);
Mat4 view_proj = proj * view;
// 1. Cylindrical Skybox (no translation, depth <= 1.0)
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_FALSE);
if (tex_sky_ && sky_vao_) {
Mat4 view_no_trans = view;
view_no_trans.m[12] = view_no_trans.m[13] = view_no_trans.m[14] = 0.0f;
sky_shader_.use();
sky_shader_.set_mat4("uViewProjNoTrans", proj * view_no_trans);
sky_shader_.set_vec3("uFogColor", fog_color_);
gl::ActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_sky_);
sky_shader_.set_int("uSkyTex", 0);
gl::BindVertexArray(sky_vao_);
glDrawArrays(GL_TRIANGLES, 0, sky_vert_count_);
}
// 2. Terrain & 3D Columns
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
world_shader_.use();
world_shader_.set_mat4("uViewProj", view_proj);
world_shader_.set_vec3("uCamPos", cam.eye);
world_shader_.set_vec3("uFogColor", fog_color_);
world_shader_.set_float("uDrawDist", draw_dist);
gl::ActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, tex_terrain_array_);
world_shader_.set_int("uTexArray", 0);
if (terrain_mesh_.vao && terrain_mesh_.index_count > 0) {
gl::BindVertexArray(terrain_mesh_.vao);
glDrawElements(GL_TRIANGLES, terrain_mesh_.index_count, GL_UNSIGNED_INT, nullptr);
}
if (column_mesh_.vao && column_mesh_.index_count > 0) {
gl::BindVertexArray(column_mesh_.vao);
glDrawElements(GL_TRIANGLES, column_mesh_.index_count, GL_UNSIGNED_INT, nullptr);
}
// 3. 3D Models (opaque first, then translucent ghosts)
glDisable(GL_CULL_FACE); // Bullfrog models mix face windings on thin fins/wings
model_shader_.use();
model_shader_.set_mat4("uViewProj", view_proj);
model_shader_.set_vec3("uCamPos", cam.eye);
model_shader_.set_vec3("uFogColor", fog_color_);
model_shader_.set_float("uDrawDist", draw_dist);
model_shader_.set_float("uEnableFog", 1.0f);
gl::ActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_);
model_shader_.set_int("uAtlas", 0);
auto draw_model = [&](const ModelInstance& inst) {
auto it = model_cache_.find(inst.model_key);
if (it == model_cache_.end() || !it->second.vao) return;
Mat4 model = Mat4::translate(inst.pos) *
Mat4::rotate_y(inst.yaw) *
Mat4::rotate_x(inst.pitch) *
Mat4::rotate_z(inst.roll) *
Mat4::scale(Vec3(inst.scale, inst.scale, inst.scale));
model_shader_.set_mat4("uModel", model);
model_shader_.set_vec4("uTint", inst.tint);
gl::BindVertexArray(it->second.vao);
glDrawElements(GL_TRIANGLES, it->second.index_count, GL_UNSIGNED_INT, nullptr);
};
for (const auto& inst : models) {
if (inst.tint.w >= 0.99f) draw_model(inst);
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_FALSE);
for (const auto& inst : models) {
if (inst.tint.w < 0.99f) draw_model(inst);
}
// 4. Particles / Explosions / Booster Flames / Minigun Tracers (additive)
if (!particles.empty() && part_vao_) {
// Extract camera right & up vectors from view matrix
Vec3 cam_right(view.m[0], view.m[4], view.m[8]);
Vec3 cam_up(view.m[1], view.m[5], view.m[9]);
std::vector<float> pverts;
pverts.reserve(particles.size() * 6 * 9);
for (const auto& p : particles) {
Vec3 rx = cam_right * (p.size * 0.5f);
Vec3 ry = cam_up * (p.size * 0.5f);
Vec3 c0 = p.pos - rx - ry;
Vec3 c1 = p.pos + rx - ry;
Vec3 c2 = p.pos + rx + ry;
Vec3 c3 = p.pos - rx + ry;
auto emit = [&](const Vec3& q, float u, float v) {
pverts.push_back(q.x); pverts.push_back(q.y); pverts.push_back(q.z);
pverts.push_back(u); pverts.push_back(v);
pverts.push_back(p.color.x); pverts.push_back(p.color.y);
pverts.push_back(p.color.z); pverts.push_back(p.color.w);
};
emit(c0, 0.0f, 0.0f); emit(c1, 1.0f, 0.0f); emit(c2, 1.0f, 1.0f);
emit(c0, 0.0f, 0.0f); emit(c2, 1.0f, 1.0f); emit(c3, 0.0f, 1.0f);
}
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
particle_shader_.use();
particle_shader_.set_mat4("uViewProj", view_proj);
gl::BindVertexArray(part_vao_);
gl::BindBuffer(GL_ARRAY_BUFFER, part_vbo_);
gl::BufferData(GL_ARRAY_BUFFER,
static_cast<GLsizeiptr>(pverts.size() * sizeof(float)),
pverts.data(), GL_DYNAMIC_DRAW);
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(particles.size() * 6));
}
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
gl::BindVertexArray(0);
}
void WorldRenderer::end_classic_world_pass(int backbuffer_w, int backbuffer_h, const GameConfig& cfg) {
if (!cfg.classic_mode || !classic_fbo_) return;
gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, backbuffer_w, backbuffer_h);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Preserve authentic 4:3 pillarboxed aspect ratio in Classic Mode
float win_aspect = static_cast<float>(backbuffer_w) / static_cast<float>(std::max(backbuffer_h, 1));
constexpr float kTargetAspect = 4.0f / 3.0f;
int vx = 0, vy = 0, vw = backbuffer_w, vh = backbuffer_h;
if (win_aspect > kTargetAspect) {
vw = static_cast<int>(static_cast<float>(backbuffer_h) * kTargetAspect);
vx = (backbuffer_w - vw) / 2;
} else {
vh = static_cast<int>(static_cast<float>(backbuffer_w) / kTargetAspect);
vy = (backbuffer_h - vh) / 2;
}
glViewport(vx, vy, vw, vh);
classic_shader_.use();
gl::ActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, classic_color_tex_);
classic_shader_.set_int("uSceneTex", 0);
gl::ActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, tex_palette_);
classic_shader_.set_int("uPaletteTex", 1);
classic_shader_.set_float("uScanlines", cfg.classic_scanlines ? 1.0f : 0.0f);
classic_shader_.set_float("uHeightPx", static_cast<float>(classic_h_));
gl::BindVertexArray(quad_vao_);
glDrawArrays(GL_TRIANGLES, 0, 6);
gl::BindVertexArray(0);
gl::ActiveTexture(GL_TEXTURE0);
glViewport(0, 0, backbuffer_w, backbuffer_h);
}
void WorldRenderer::render_model_preview(const std::string& model_key, float yaw_rad,
int vx, int vy, int vw, int vh, float scale) {
auto it = model_cache_.find(model_key);
if (it == model_cache_.end() || !it->second.vao || vw <= 0 || vh <= 0) return;
glViewport(vx, vy, vw, vh);
glEnable(GL_DEPTH_TEST);
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
float aspect = static_cast<float>(vw) / static_cast<float>(vh);
Mat4 proj = Mat4::perspective(deg_to_rad(42.0f), aspect, 0.1f, 20.0f);
Mat4 view = Mat4::look_at(Vec3(0.0f, 1.1f, 2.7f), Vec3(0.0f, 0.05f, 0.0f), Vec3(0, 1, 0));
Mat4 model = Mat4::rotate_y(yaw_rad) * Mat4::scale(Vec3(scale, scale, scale));
model_shader_.use();
model_shader_.set_mat4("uViewProj", proj * view);
model_shader_.set_mat4("uModel", model);
model_shader_.set_vec4("uTint", Vec4(1, 1, 1, 1));
model_shader_.set_float("uEnableFog", 0.0f);
gl::ActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_);
model_shader_.set_int("uAtlas", 0);
gl::BindVertexArray(it->second.vao);
glDrawElements(GL_TRIANGLES, it->second.index_count, GL_UNSIGNED_INT, nullptr);
gl::BindVertexArray(0);
}
} // namespace top_octane::render
+134
View File
@@ -0,0 +1,134 @@
#pragma once
#include "assets/level.hpp"
#include "assets/model.hpp"
#include "assets/palette.hpp"
#include "assets/textures.hpp"
#include "core/config.hpp"
#include "core/math.hpp"
#include "core/vfs.hpp"
#include "render/gl_api.hpp"
#include "render/shader.hpp"
#include "render/world_geometry.hpp"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace top_octane::render {
struct RenderCamera {
Vec3 eye{0.0f, 3.0f, 0.0f};
Vec3 target{0.0f, 0.0f, -5.0f};
Vec3 up{0.0f, 1.0f, 0.0f};
float fov_deg = 70.0f;
float z_near = 0.1f;
float z_far = 160.0f;
};
struct ModelInstance {
std::string model_key; // e.g. "CAR0-0", "BAREL0-0", "RECOV0-0"
Vec3 pos{0.0f, 0.0f, 0.0f};
float yaw = 0.0f; // radians around +Y
float pitch = 0.0f; // radians around local +X
float roll = 0.0f; // radians around local +Z
float scale = 1.0f;
Vec4 tint{1.0f, 1.0f, 1.0f, 1.0f}; // rgb multiplier, a < 1 for ghost/transparent
};
struct ParticleQuad {
Vec3 pos;
float size = 0.4f;
Vec4 color{1.0f, 0.8f, 0.3f, 1.0f};
};
class WorldRenderer {
public:
WorldRenderer() = default;
~WorldRenderer();
WorldRenderer(const WorldRenderer&) = delete;
WorldRenderer& operator=(const WorldRenderer&) = delete;
bool init(const Vfs& vfs, const assets::Palette& pal);
void shutdown();
bool load_level(const Vfs& vfs, const assets::LevelData& level, const assets::Palette& pal);
void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x1, int z1);
// Preloads a 3D model from OBJECTS/DATA/<key>.DAT (cached by key)
bool ensure_model(const Vfs& vfs, const std::string& key, const assets::Palette& pal);
void begin_frame(int backbuffer_w, int backbuffer_h, const GameConfig& cfg);
// viewport_index: 0 = full screen (when split_count == 1), 0 = top / 1 = bottom (when split_count == 2)
void render_world_view(const RenderCamera& cam, const std::vector<ModelInstance>& models,
const std::vector<ParticleQuad>& particles,
int viewport_index, int split_count, const GameConfig& cfg);
// Finalizes Classic Mode FBO quantization blit if active; call before drawing crisp 2D UI or after
void end_classic_world_pass(int backbuffer_w, int backbuffer_h, const GameConfig& cfg);
// Standalone rotating model preview (for Vehicle Select screen)
void render_model_preview(const std::string& model_key, float yaw_rad,
int vx, int vy, int vw, int vh, float scale = 1.0f);
const WorldGeometry& geometry() const { return world_geo_; }
const assets::ObjectTextureAtlas& object_atlas() const { return obj_atlas_; }
private:
struct GpuMesh {
GLuint vao = 0;
GLuint vbo = 0;
GLuint ebo = 0;
GLsizei index_count = 0;
};
void destroy_mesh(GpuMesh& m);
void upload_world_mesh(GpuMesh& m, const std::vector<WorldVertex>& verts,
const std::vector<uint32_t>& indices, bool dynamic);
void ensure_classic_fbo(int w, int h);
void apply_texture_filtering(TextureFilterMode mode);
bool initialized_ = false;
assets::ObjectTextureAtlas obj_atlas_;
assets::ColorTables color_tables_;
assets::WorldTextures world_textures_;
WorldGeometry world_geo_;
// Shaders
ShaderProgram world_shader_;
ShaderProgram model_shader_;
ShaderProgram sky_shader_;
ShaderProgram particle_shader_;
ShaderProgram classic_shader_;
// Textures
GLuint tex_terrain_array_ = 0;
GLuint tex_sky_ = 0;
GLuint tex_obj_atlas_ = 0;
GLuint tex_palette_ = 0;
TextureFilterMode active_filter_ = TextureFilterMode::Linear;
// World meshes
GpuMesh terrain_mesh_;
GpuMesh column_mesh_;
GLuint sky_vao_ = 0, sky_vbo_ = 0;
int sky_vert_count_ = 0;
// Dynamic particles
GLuint part_vao_ = 0, part_vbo_ = 0;
// Fullscreen quad & Classic Mode FBO
GLuint quad_vao_ = 0, quad_vbo_ = 0;
GLuint classic_fbo_ = 0, classic_color_tex_ = 0, classic_depth_rbo_ = 0;
int classic_w_ = 0, classic_h_ = 0;
int backbuffer_w_ = 1280, backbuffer_h_ = 720;
// Cached 3D models
std::unordered_map<std::string, GpuMesh> model_cache_;
Vec3 fog_color_{0.15f, 0.2f, 0.3f};
};
} // namespace top_octane::render
+166
View File
@@ -0,0 +1,166 @@
#include "sim/ai_driver.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::sim {
CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level,
const std::vector<CraftState>& all_crafts, int difficulty) {
CraftInput out;
if (ai.recovery_state != RecoveryState::Active || level.main_waypoints.empty()) {
return out;
}
int n_wp = static_cast<int>(level.main_waypoints.size());
int wp_idx = ai.ai_target_wp % n_wp;
const auto& cur_wp = level.main_waypoints[wp_idx];
Vec2 to_wp(cur_wp.x - ai.curr_pose.pos.x, cur_wp.z - ai.curr_pose.pos.z);
if (to_wp.len() < 5.0f) {
ai.ai_target_wp = (wp_idx + 1) % n_wp;
wp_idx = ai.ai_target_wp;
}
// Decide whether to detour briefly over a nearby recharge pad when low on fuel or shield
Vec2 tgt_pos(level.main_waypoints[wp_idx].x, level.main_waypoints[wp_idx].z);
if ((ai.fuel < ai.max_fuel * 0.25f || ai.shield < ai.max_shield * 0.28f) && !level.pads.empty()) {
for (const auto& pad : level.pads) {
Vec2 p(pad.tile_x() + 0.5f, pad.tile_z() + 0.5f);
float d2 = (p - Vec2(ai.curr_pose.pos.x, ai.curr_pose.pos.z)).len_sq();
if (d2 < 14.0f * 14.0f) {
tgt_pos = p;
ai.ai_seeking_pit = true;
break;
}
}
} else {
ai.ai_seeking_pit = false;
}
// Spread AI racing lines gently so racers overtake instead of forming a single line
if (!ai.ai_seeking_pit) {
const auto& nxt = level.main_waypoints[(wp_idx + 1) % n_wp];
Vec2 seg = Vec2(nxt.x - tgt_pos.x, nxt.z - tgt_pos.y).normalized();
Vec2 right(-seg.y, seg.x);
float lane = (static_cast<float>((ai.id % 5) - 2)) * 0.55f;
Vec2 shifted = tgt_pos + right * lane;
if (!level.is_cell_solid_at_y(static_cast<int>(std::floor(shifted.x)),
static_cast<int>(std::floor(shifted.y)),
ai.curr_pose.pos.y)) {
tgt_pos = shifted;
}
}
// Forward column-obstacle lookahead & lateral bypass lane selection
Vec2 cur_pos(ai.curr_pose.pos.x, ai.curr_pose.pos.z);
Vec2 to_tgt = tgt_pos - cur_pos;
float tgt_dist = to_tgt.len();
Vec2 base_dir = (tgt_dist > 1e-3f)
? (to_tgt * (1.0f / tgt_dist))
: Vec2(std::sin(ai.curr_pose.yaw), std::cos(ai.curr_pose.yaw));
float hit_dist = -1.0f;
float max_probe = std::min(tgt_dist, 7.5f);
for (float d = 1.0f; d <= max_probe; d += 0.75f) {
Vec2 p = cur_pos + base_dir * d;
if (level.is_cell_solid_at_y(static_cast<int>(std::floor(p.x)),
static_cast<int>(std::floor(p.y)),
ai.curr_pose.pos.y)) {
hit_dist = d;
break;
}
}
if (hit_dist > 0.0f) {
Vec2 perp(-base_dir.y, base_dir.x);
const float probe_ds[3] = {hit_dist * 0.5f, hit_dist, hit_dist + 2.0f};
const float offs[5] = {1.5f, 2.5f, 3.5f, 4.5f, 5.5f};
bool found_bypass = false;
float best_side = 1.0f;
float best_off = 3.5f;
for (float off : offs) {
for (float side : {-1.0f, 1.0f}) {
bool clear = true;
for (float pd : probe_ds) {
Vec2 p = cur_pos + base_dir * pd + perp * (side * off);
if (p.x < 2.0f || p.x > assets::kMapWidth - 3.0f ||
p.y < 2.0f || p.y > assets::kMapHeight - 3.0f ||
level.is_cell_solid_at_y(static_cast<int>(std::floor(p.x)),
static_cast<int>(std::floor(p.y)),
ai.curr_pose.pos.y)) {
clear = false;
break;
}
}
if (clear) {
best_side = side;
best_off = off;
found_bypass = true;
break;
}
}
if (found_bypass) break;
}
if (found_bypass) {
tgt_pos = cur_pos + base_dir * std::max(hit_dist, 2.5f) + perp * (best_side * (best_off + 0.6f));
}
}
// Craft avoidance repulsion
Vec2 avoid(0.0f, 0.0f);
for (const auto& other : all_crafts) {
if (other.id == ai.id || other.recovery_state != RecoveryState::Active) continue;
Vec2 d(ai.curr_pose.pos.x - other.curr_pose.pos.x, ai.curr_pose.pos.z - other.curr_pose.pos.z);
float dist_sq = d.len_sq();
if (dist_sq > 0.01f && dist_sq < 2.25f) {
avoid = avoid + d.normalized() * (1.2f / std::sqrt(dist_sq));
}
}
Vec2 aim = (tgt_pos - cur_pos).normalized() + avoid * 0.45f;
float desired_yaw = std::atan2(aim.x, aim.y);
float err = wrap_angle(desired_yaw - ai.curr_pose.yaw);
out.steer = std::clamp(-err * 1.85f, -1.0f, 1.0f);
float diff_pace = (difficulty == 0) ? 0.78f : (difficulty == 2 ? 1.0f : 0.90f);
float spd = ai.speed_horizontal();
bool is_corner = (level.main_waypoints[wp_idx].subtype == 1);
if (hit_dist > 0.0f && hit_dist < 1.6f && spd < 1.2f && ai.race_time > 1.5f) {
out.throttle = 0.0f;
out.brake = 0.65f;
} else if (std::abs(err) > 0.65f && spd > 9.5f) {
out.throttle = 0.25f * diff_pace;
out.brake = 0.35f;
} else if (is_corner && spd > 13.0f * diff_pace) {
out.throttle = 0.50f * diff_pace;
} else {
out.throttle = diff_pace;
if (difficulty >= 1 && std::abs(err) < 0.18f && ai.fuel > ai.max_fuel * 0.45f &&
(ai.id + static_cast<int>(ai.race_time)) % 3 == 0) {
out.boost = true;
}
}
// Combat AI: shoot opponents in sights!
if (ai.ammo > 5.0f) {
Vec3 fwd = ai.forward_dir();
for (const auto& other : all_crafts) {
if (other.id == ai.id || other.recovery_state != RecoveryState::Active) continue;
Vec3 to_e = other.curr_pose.pos - ai.curr_pose.pos;
float dist = to_e.len();
if (dist < 1.2f || dist > 22.0f) continue;
float cos_ang = (to_e / dist).dot(fwd);
if (cos_ang > 0.93f && difficulty >= 0) {
out.fire_minigun = (difficulty == 2 || (static_cast<int>(ai.race_time * 10.0f) % 2 == 0));
}
}
if (ai.lock_progress >= 1.0f && difficulty >= 1 && ai.ammo >= 20.0f) {
out.fire_missile = true;
}
}
return out;
}
} // namespace top_octane::sim
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "assets/level.hpp"
#include "input/input_manager.hpp"
#include "sim/physics.hpp"
#include <vector>
namespace top_octane::sim {
// Computes autonomous steering, throttle, boost, pit detour, and weapon inputs for an AI craft
CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level,
const std::vector<CraftState>& all_crafts, int difficulty);
} // namespace top_octane::sim
+440
View File
@@ -0,0 +1,440 @@
#include "sim/combat.hpp"
#include "sim/vehicle_defs.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::sim {
namespace {
void spawn_explosion(std::vector<ParticleBurst>& particles, const Vec3& pos, float scale = 1.0f) {
for (int k = 0; k < 10; ++k) {
float ang = kTwoPi * (static_cast<float>(k) / 10.0f);
float spd = (1.5f + static_cast<float>((k * 37) % 10) * 0.28f) * scale;
Vec3 v(std::cos(ang) * spd, (1.2f + static_cast<float>(k % 3) * 0.9f) * scale,
std::sin(ang) * spd);
Vec4 col = (k % 2 == 0) ? Vec4(1.0f, 0.6f, 0.15f, 1.0f) : Vec4(1.0f, 0.25f, 0.05f, 1.0f);
particles.push_back({pos, v, 0.55f * scale, col, 0.45f, 0.45f});
}
}
void apply_damage(CraftState& victim, int attacker_id, const std::vector<CraftState>& crafts,
const RaceSetup& setup, std::vector<ParticleBurst>& particles,
std::vector<SimEvent>& events, bool& out_race_over, int& out_winner_id) {
(void)setup;
if (victim.recovery_state != RecoveryState::Active) return;
victim.damage_flash = 0.22f;
if (victim.shield > 0.0f) return;
// Craft destroyed!
victim.shield = 0.0f;
victim.deaths += 1;
victim.vel = Vec3(0, 0, 0);
victim.recovery_state = RecoveryState::CallingRepair;
victim.recovery_timer = 3.2f;
victim.recovery_pos = victim.curr_pose.pos;
std::string killer_name = "TRACK";
if (attacker_id >= 0 && attacker_id < static_cast<int>(crafts.size())) {
killer_name = crafts[attacker_id].pilot_name;
}
victim.killed_by = killer_name;
spawn_explosion(particles, victim.curr_pose.pos, 1.5f);
events.push_back({SimSoundCue::Explosion, victim.curr_pose.pos,
victim.is_human ? victim.player_index : -1,
victim.is_human ? ("KILLED BY " + killer_name) : "", 0.95f});
// Credit kill to attacker (const_cast avoided by updating in caller if needed, see below)
(void)out_race_over;
(void)out_winner_id;
}
void apply_pickup(CraftState& c, uint8_t subtype, std::vector<SimEvent>& events) {
// Map Bullfrog type-5 subtypes to authentic Hi-Octane powerups
std::string msg;
SimSoundCue cue = SimSoundCue::Pickup;
switch (subtype) {
case 0:
case 1:
c.fuel = std::min(c.max_fuel, c.fuel + 35.0f);
msg = "FUEL";
break;
case 2:
c.max_fuel = std::min(220.0f, c.max_fuel + 25.0f);
c.fuel = c.max_fuel;
msg = "EXTRA FUEL";
cue = SimSoundCue::Powerup;
break;
case 3:
c.shield = std::min(c.max_shield, c.shield + 40.0f);
msg = "SHIELD";
break;
case 4:
case 5:
c.max_shield = std::min(260.0f, c.max_shield + 30.0f);
c.shield = c.max_shield;
msg = "EXTRA SHIELD";
cue = SimSoundCue::Powerup;
break;
case 6:
case 7:
c.ammo = std::min(c.max_ammo, c.ammo + 45.0f);
msg = "AMMO";
break;
case 8:
case 9:
c.max_ammo = std::min(250.0f, c.max_ammo + 30.0f);
c.ammo = c.max_ammo;
msg = "EXTRA AMMO";
cue = SimSoundCue::Powerup;
break;
case 10:
c.booster_level = std::min(3, c.booster_level + 1);
c.fuel = std::min(c.max_fuel, c.fuel + 30.0f);
msg = "BOOSTER UPGRADED";
cue = SimSoundCue::Powerup;
break;
case 11:
c.minigun_level = std::min(3, c.minigun_level + 1);
c.ammo = std::min(c.max_ammo, c.ammo + 35.0f);
msg = "MINIGUN UPGRADED";
cue = SimSoundCue::Powerup;
break;
case 12:
case 13:
default:
c.missile_level = std::min(3, c.missile_level + 1);
c.ammo = std::min(c.max_ammo, c.ammo + 35.0f);
msg = "MISSILE UPGRADED";
cue = SimSoundCue::Powerup;
break;
}
events.push_back({cue, c.curr_pose.pos, c.is_human ? c.player_index : -1,
c.is_human ? msg : "", 0.25f});
}
} // namespace
void step_combat_and_world(
RaceSetup& setup,
const assets::LevelData& level,
std::vector<CraftState>& crafts,
const std::vector<CraftInput>& inputs,
std::vector<Projectile>& projectiles,
std::vector<PickupItem>& pickups,
std::vector<PropObject>& props,
std::vector<ParticleBurst>& particles,
std::vector<SimEvent>& events,
bool& out_race_over,
int& out_winner_id,
float dt) {
// 1. Recovery craft state machine & weapon firing per craft
for (size_t i = 0; i < crafts.size(); ++i) {
CraftState& c = crafts[i];
if (c.recovery_state != RecoveryState::Active) {
c.recovery_timer -= dt;
if (c.recovery_state == RecoveryState::CallingRepair && c.recovery_timer < 2.2f) {
c.recovery_state = RecoveryState::AwaitingRepair;
if (c.is_human) {
events.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index, "AWAITING REPAIR", 0.0f});
}
} else if (c.recovery_state == RecoveryState::AwaitingRepair && c.recovery_timer < 1.1f) {
c.recovery_state = RecoveryState::Repairing;
if (c.is_human) {
events.push_back({SimSoundCue::Refuel, c.curr_pose.pos, c.player_index, "REPAIRING", 0.0f});
}
} else if (c.recovery_timer <= 0.0f) {
c.recovery_state = RecoveryState::Active;
c.shield = c.max_shield;
c.fuel = c.max_fuel;
c.ammo = std::max(c.ammo, c.max_ammo * 0.5f);
// Place gently at nearest main waypoint if available
if (!level.main_waypoints.empty()) {
const auto& wp = level.main_waypoints[c.current_wp % level.main_waypoints.size()];
const auto& wpn = level.main_waypoints[(c.current_wp + 1) % level.main_waypoints.size()];
c.curr_pose.pos = Vec3(wp.x, level.sample_height_world(wp.x, wp.z) + 0.45f, wp.z);
c.curr_pose.yaw = std::atan2(wpn.x - wp.x, wpn.z - wp.z);
c.prev_pose = c.curr_pose;
c.vel = Vec3(0, 0, 0);
}
}
continue;
}
// Trigger repair if fuel completely depleted and stopped
if (c.fuel <= 0.05f && c.speed_horizontal() < 0.8f) {
c.recovery_state = RecoveryState::CallingRepair;
c.recovery_timer = 3.0f;
if (c.is_human) {
events.push_back({SimSoundCue::Warning, c.curr_pose.pos, c.player_index, "CALLING REPAIR", 0.2f});
}
continue;
}
// Update missile lock-on cone
Vec3 fwd = c.forward_dir();
int best_tgt = -1;
float best_score = 0.72f; // ~44 deg half-cone
for (size_t j = 0; j < crafts.size(); ++j) {
if (i == j || crafts[j].recovery_state != RecoveryState::Active) continue;
Vec3 to_tgt = crafts[j].curr_pose.pos - c.curr_pose.pos;
float dist = to_tgt.len();
if (dist < 1.0f || dist > 38.0f) continue;
float align = (to_tgt / dist).dot(fwd);
if (align > best_score) {
best_score = align;
best_tgt = static_cast<int>(j);
}
}
if (best_tgt >= 0) {
if (c.lock_target_id != best_tgt) {
c.lock_target_id = best_tgt;
c.lock_progress = 0.0f;
}
float prev_lock = c.lock_progress;
float lock_speed = 1.4f + 0.4f * static_cast<float>(c.missile_level - 1);
c.lock_progress = std::min(1.0f, c.lock_progress + lock_speed * dt);
if (prev_lock < 1.0f && c.lock_progress >= 1.0f && c.is_human) {
events.push_back({SimSoundCue::LockOn, c.curr_pose.pos, c.player_index, "", 0.1f});
}
} else {
c.lock_target_id = -1;
c.lock_progress = 0.0f;
}
const CraftInput& in = (i < inputs.size()) ? inputs[i] : CraftInput{};
const VehicleSpec& sp = kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)];
// Fire Minigun
if (in.fire_minigun && c.minigun_cd <= 0.0f && c.ammo >= 1.0f) {
c.ammo -= 1.0f;
c.minigun_cd = std::max(0.06f, 0.13f - 0.025f * static_cast<float>(c.minigun_level - 1));
c.shots_fired += 1;
float dmg = sp.minigun_damage * (1.0f + 0.25f * static_cast<float>(c.minigun_level - 1));
Projectile p;
p.active = true;
p.is_missile = false;
p.owner_id = c.id;
p.pos = c.curr_pose.pos + fwd * 0.7f + Vec3(0, 0.1f, 0);
p.vel = fwd * 48.0f + c.vel * 0.35f;
p.yaw = c.curr_pose.yaw;
p.damage = dmg;
p.life = 1.1f;
projectiles.push_back(p);
events.push_back({SimSoundCue::MinigunShot, c.curr_pose.pos, c.player_index, "", 0.08f});
}
// Fire Homing Missile
if (in.fire_missile && c.missile_cd <= 0.0f && c.ammo >= 12.0f) {
c.ammo -= 12.0f;
c.missile_cd = std::max(0.45f, 0.85f - 0.14f * static_cast<float>(c.missile_level - 1));
c.shots_fired += 1;
float dmg = sp.missile_damage * (1.0f + 0.22f * static_cast<float>(c.missile_level - 1));
Projectile p;
p.active = true;
p.is_missile = true;
p.owner_id = c.id;
p.target_id = (c.lock_progress >= 0.75f) ? c.lock_target_id : -1;
p.pos = c.curr_pose.pos + fwd * 0.85f + Vec3(0, 0.15f, 0);
p.vel = fwd * 30.0f + c.vel * 0.3f;
p.yaw = c.curr_pose.yaw;
p.damage = dmg;
p.life = 2.8f;
projectiles.push_back(p);
events.push_back({SimSoundCue::MissileLaunch, c.curr_pose.pos, c.player_index, "", 0.30f});
}
}
// 2. Step Projectiles & Hit Detection
for (auto& pr : projectiles) {
if (!pr.active) continue;
pr.life -= dt;
if (pr.life <= 0.0f) {
pr.active = false;
continue;
}
if (pr.is_missile && pr.target_id >= 0 && pr.target_id < static_cast<int>(crafts.size())) {
const CraftState& tgt = crafts[pr.target_id];
if (tgt.recovery_state == RecoveryState::Active) {
Vec3 to_tgt = (tgt.curr_pose.pos - pr.pos).normalized();
Vec3 dir = pr.vel.normalized();
float spd = pr.vel.len();
Vec3 steered = lerp(dir, to_tgt, std::min(1.0f, dt * 6.5f)).normalized();
pr.vel = steered * std::max(spd, 28.0f);
pr.yaw = std::atan2(steered.x, steered.z);
}
particles.push_back({pr.pos, Vec3(0, 0.3f, 0), 0.24f, Vec4(0.95f, 0.8f, 0.45f, 0.8f), 0.18f, 0.18f});
} else if (!pr.is_missile) {
particles.push_back({pr.pos, Vec3(0, 0, 0), 0.14f, Vec4(1.0f, 0.95f, 0.4f, 0.9f), 0.06f, 0.06f});
}
pr.pos += pr.vel * dt;
// World/Column/Ground impact
float gy = level.sample_height_world(pr.pos.x, pr.pos.z);
if (pr.pos.y <= gy ||
level.is_cell_solid_at_y(static_cast<int>(std::floor(pr.pos.x)),
static_cast<int>(std::floor(pr.pos.z)), pr.pos.y)) {
pr.active = false;
if (pr.is_missile) {
spawn_explosion(particles, pr.pos, 0.9f);
events.push_back({SimSoundCue::Explosion, pr.pos, -1, "", 0.0f});
} else {
particles.push_back({pr.pos, Vec3(0, 1.0f, 0), 0.22f, Vec4(1.0f, 0.8f, 0.3f, 0.9f), 0.16f, 0.16f});
}
continue;
}
// Hit Crafts
for (size_t j = 0; j < crafts.size(); ++j) {
CraftState& victim = crafts[j];
if (victim.id == pr.owner_id || victim.recovery_state != RecoveryState::Active) continue;
const VehicleSpec& vspec = kVehicleSpecs[std::clamp(victim.vehicle_idx, 0, 5)];
float hit_r = vspec.collision_radius + 0.12f;
Vec3 d = victim.curr_pose.pos - pr.pos;
if (d.len_sq() < hit_r * hit_r) {
pr.active = false;
victim.shield -= pr.damage;
victim.armour_used += pr.damage;
if (pr.owner_id >= 0 && pr.owner_id < static_cast<int>(crafts.size())) {
crafts[pr.owner_id].shots_hit += 1;
}
if (pr.is_missile) {
spawn_explosion(particles, pr.pos, 1.15f);
events.push_back({SimSoundCue::Explosion, pr.pos,
victim.is_human ? victim.player_index : -1, "", 0.65f});
} else {
particles.push_back({pr.pos, Vec3(0, 1.2f, 0), 0.28f, Vec4(1.0f, 0.6f, 0.2f, 1.0f), 0.20f, 0.20f});
events.push_back({SimSoundCue::Impact, pr.pos,
victim.is_human ? victim.player_index : -1, "", 0.20f});
}
if (victim.shield <= 0.0f) {
if (pr.owner_id >= 0 && pr.owner_id < static_cast<int>(crafts.size())) {
crafts[pr.owner_id].kills += 1;
if (setup.mode == GameMode::DeathMatch &&
crafts[pr.owner_id].kills >= setup.deathmatch_kill_limit) {
out_race_over = true;
out_winner_id = crafts[pr.owner_id].id;
}
}
apply_damage(victim, pr.owner_id, crafts, setup, particles, events,
out_race_over, out_winner_id);
}
break;
}
}
if (!pr.active) continue;
// Hit Destructible Props
for (auto& prop : props) {
if (!prop.alive) continue;
if ((prop.pos - pr.pos).len_sq() < 0.60f * 0.60f) {
pr.active = false;
prop.hp -= pr.damage;
if (prop.hp <= 0.0f) {
prop.alive = false;
prop.respawn_timer = 25.0f;
spawn_explosion(particles, prop.pos, 0.85f);
events.push_back({SimSoundCue::Explosion, prop.pos, -1, "", 0.25f});
}
break;
}
}
}
projectiles.erase(
std::remove_if(projectiles.begin(), projectiles.end(),
[](const Projectile& p) { return !p.active; }),
projectiles.end());
// 3. Pickups collection & respawn
for (auto& pk : pickups) {
if (!pk.active) {
pk.respawn_timer -= dt;
if (pk.respawn_timer <= 0.0f) pk.active = true;
continue;
}
for (auto& c : crafts) {
if (c.recovery_state != RecoveryState::Active) continue;
const VehicleSpec& sp = kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)];
float pick_r = sp.collision_radius + 0.45f;
Vec3 d = c.curr_pose.pos - pk.pos;
if (d.x * d.x + d.z * d.z < pick_r * pick_r && std::abs(d.y) < 1.5f) {
pk.active = false;
pk.respawn_timer = 15.0f;
apply_pickup(c, pk.subtype, events);
break;
}
}
}
// 4. Prop collision & respawn
for (auto& prop : props) {
if (!prop.alive) {
prop.respawn_timer -= dt;
if (prop.respawn_timer <= 0.0f) {
prop.alive = true;
prop.hp = 25.0f;
}
continue;
}
for (auto& c : crafts) {
if (c.recovery_state != RecoveryState::Active) continue;
const VehicleSpec& sp = kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)];
float prop_r = sp.collision_radius + 0.24f;
Vec3 d = c.curr_pose.pos - prop.pos;
if (d.x * d.x + d.z * d.z < prop_r * prop_r && std::abs(d.y) < 1.2f) {
prop.alive = false;
prop.respawn_timer = 25.0f;
if (prop.model_key.rfind("BAREL", 0) == 0) {
c.shield = std::max(5.0f, c.shield - 12.0f);
spawn_explosion(particles, prop.pos, 0.9f);
events.push_back({SimSoundCue::Explosion, prop.pos,
c.is_human ? c.player_index : -1, "", 0.45f});
} else {
events.push_back({SimSoundCue::Impact, prop.pos,
c.is_human ? c.player_index : -1, "", 0.12f});
}
break;
}
}
}
}
std::vector<RecoveryVisual> get_recovery_visuals(const std::vector<CraftState>& crafts) {
std::vector<RecoveryVisual> out;
for (const auto& c : crafts) {
if (c.recovery_state == RecoveryState::CallingRepair ||
c.recovery_state == RecoveryState::AwaitingRepair ||
c.recovery_state == RecoveryState::Repairing) {
RecoveryVisual rv;
rv.active = true;
float hover_y = 0.0f;
if (c.recovery_state == RecoveryState::CallingRepair) {
float t = std::clamp((c.recovery_timer - 2.2f) / 1.0f, 0.0f, 1.0f);
hover_y = 1.6f + t * 8.0f;
} else if (c.recovery_state == RecoveryState::AwaitingRepair) {
float t = std::clamp((c.recovery_timer - 1.1f) / 1.1f, 0.0f, 1.0f);
hover_y = 1.05f + t * 0.55f;
} else {
hover_y = 1.05f;
}
rv.pos = c.curr_pose.pos + Vec3(0.0f, hover_y, 0.0f);
rv.yaw = c.curr_pose.yaw;
out.push_back(rv);
}
}
return out;
}
} // namespace top_octane::sim
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "sim/race_sim.hpp"
#include <vector>
namespace top_octane::sim {
struct RecoveryVisual {
bool active = false;
Vec3 pos{0, 0, 0};
float yaw = 0.0f;
};
// Updates forward-cone missile lock, weapon firing, projectile movement, collisions, pickups, props & recovery
void step_combat_and_world(
RaceSetup& setup,
const assets::LevelData& level,
std::vector<CraftState>& crafts,
const std::vector<CraftInput>& inputs,
std::vector<Projectile>& projectiles,
std::vector<PickupItem>& pickups,
std::vector<PropObject>& props,
std::vector<ParticleBurst>& particles,
std::vector<SimEvent>& events,
bool& out_race_over,
int& out_winner_id,
float dt);
// Computes visual Recovery Helicopter (RECOV0-0) positions for any craft under repair
std::vector<RecoveryVisual> get_recovery_visuals(const std::vector<CraftState>& crafts);
} // namespace top_octane::sim
+450
View File
@@ -0,0 +1,450 @@
#include "sim/physics.hpp"
#include <algorithm>
#include <cmath>
namespace top_octane::sim {
namespace {
constexpr float kGravity = 13.5f;
constexpr float kWallBounce = 0.32f;
} // namespace
bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level,
float& out_impact_speed, bool& out_scraping) {
out_impact_speed = 0.0f;
out_scraping = false;
if (craft.recovery_state != RecoveryState::Active) {
return false;
}
const VehicleSpec& spec = kVehicleSpecs[std::clamp(craft.vehicle_idx, 0, 5)];
const float radius = spec.collision_radius;
bool hit = false;
auto record_impact = [&](float vn_mag) {
hit = true;
out_impact_speed = std::max(out_impact_speed, vn_mag);
if (vn_mag < 4.5f) {
out_scraping = true;
}
};
// Map boundary clamping
constexpr float kMargin = 1.5f;
if (craft.curr_pose.pos.x < kMargin) {
craft.curr_pose.pos.x = kMargin;
if (craft.vel.x < 0.0f) {
record_impact(-craft.vel.x);
craft.vel.x = -craft.vel.x * kWallBounce;
} else {
hit = true;
}
} else if (craft.curr_pose.pos.x > assets::kMapWidth - 1.0f - kMargin) {
craft.curr_pose.pos.x = assets::kMapWidth - 1.0f - kMargin;
if (craft.vel.x > 0.0f) {
record_impact(craft.vel.x);
craft.vel.x = -craft.vel.x * kWallBounce;
} else {
hit = true;
}
}
if (craft.curr_pose.pos.z < kMargin) {
craft.curr_pose.pos.z = kMargin;
if (craft.vel.z < 0.0f) {
record_impact(-craft.vel.z);
craft.vel.z = -craft.vel.z * kWallBounce;
} else {
hit = true;
}
} else if (craft.curr_pose.pos.z > assets::kMapHeight - 1.0f - kMargin) {
craft.curr_pose.pos.z = assets::kMapHeight - 1.0f - kMargin;
if (craft.vel.z > 0.0f) {
record_impact(craft.vel.z);
craft.vel.z = -craft.vel.z * kWallBounce;
} else {
hit = true;
}
}
// Overhead gantry / tunnel ceiling clamp (before horizontal column pushout so crafts clear slot 1+)
float floor_y = 0.0f;
float ceil_y = 1e6f;
level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z,
craft.curr_pose.pos.y, floor_y, ceil_y);
if (ceil_y < 1e5f) {
float max_craft_y = std::max(floor_y + 0.14f, ceil_y - 0.46f);
if (craft.curr_pose.pos.y > max_craft_y) {
craft.curr_pose.pos.y = max_craft_y;
if (craft.vel.y > 0.0f) {
craft.vel.y = 0.0f;
}
}
}
// 2-pass seam-free 3D Column AABB vs Craft Circle pushout
for (int pass = 0; pass < 2; ++pass) {
int cx = static_cast<int>(std::floor(craft.curr_pose.pos.x));
int cz = static_cast<int>(std::floor(craft.curr_pose.pos.z));
for (int nz = cz - 1; nz <= cz + 1; ++nz) {
for (int nx = cx - 1; nx <= cx + 1; ++nx) {
if (!level.is_cell_solid_at_y(nx, nz, craft.curr_pose.pos.y)) {
continue;
}
float min_x = static_cast<float>(nx);
float max_x = min_x + 1.0f;
float min_z = static_cast<float>(nz);
float max_z = min_z + 1.0f;
float closest_x = std::clamp(craft.curr_pose.pos.x, min_x, max_x);
float closest_z = std::clamp(craft.curr_pose.pos.z, min_z, max_z);
float dx = craft.curr_pose.pos.x - closest_x;
float dz = craft.curr_pose.pos.z - closest_z;
float dist_sq = dx * dx + dz * dz;
if (dist_sq >= radius * radius) {
continue;
}
Vec2 norm;
float pen = 0.0f;
bool inside_box = (dist_sq <= 1e-8f);
if (!inside_box) {
float dist = std::sqrt(dist_sq);
norm = Vec2(dx / dist, dz / dist);
pen = radius - dist;
} else {
float dL = std::abs(craft.curr_pose.pos.x - min_x);
float dR = std::abs(max_x - craft.curr_pose.pos.x);
float dT = std::abs(craft.curr_pose.pos.z - min_z);
float dB = std::abs(max_z - craft.curr_pose.pos.z);
float md = std::min({dL, dR, dT, dB});
if (md == dL) norm = Vec2(-1, 0);
else if (md == dR) norm = Vec2(1, 0);
else if (md == dT) norm = Vec2(0, -1);
else norm = Vec2(0, 1);
pen = radius + md;
}
// Suppress internal AABB seams between adjacent solid columns of compatible height
float h_here = level.cell_height_world(nx, nz);
if (std::abs(norm.x) > 0.15f) {
int adj_x = nx + (norm.x > 0.0f ? 1 : -1);
if (level.is_cell_solid_at_y(adj_x, nz, craft.curr_pose.pos.y) &&
std::abs(level.cell_height_world(adj_x, nz) - h_here) < 0.35f) {
norm.x = 0.0f;
}
}
if (std::abs(norm.y) > 0.15f) {
int adj_z = nz + (norm.y > 0.0f ? 1 : -1);
if (level.is_cell_solid_at_y(nx, adj_z, craft.curr_pose.pos.y) &&
std::abs(level.cell_height_world(nx, adj_z) - h_here) < 0.35f) {
norm.y = 0.0f;
}
}
float nlen = std::sqrt(norm.x * norm.x + norm.y * norm.y);
if (nlen < 1e-4f) {
continue;
}
norm.x /= nlen;
norm.y /= nlen;
if (!inside_box) {
pen = radius - (dx * norm.x + dz * norm.y);
if (pen <= 0.0f) continue;
}
craft.curr_pose.pos.x += norm.x * pen;
craft.curr_pose.pos.z += norm.y * pen;
float vn = craft.vel.x * norm.x + craft.vel.z * norm.y;
if (vn < 0.0f) {
record_impact(-vn);
craft.vel.x -= (1.0f + kWallBounce) * vn * norm.x;
craft.vel.z -= (1.0f + kWallBounce) * vn * norm.y;
// Gentle tangential drag along wall without stalling slide speed
craft.vel.x *= 0.985f;
craft.vel.z *= 0.985f;
} else if (pen > 0.02f) {
hit = true;
}
}
}
}
// Steep cliff deflection (sheer cliffs have surf_n.y < 0.49; steepest Track 5 road is ~0.535)
if (!craft.airborne) {
Vec3 surf_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z);
if (surf_n.y < 0.49f) {
float hn_len = std::sqrt(surf_n.x * surf_n.x + surf_n.z * surf_n.z);
if (hn_len > 1e-4f) {
Vec2 cliff_n(surf_n.x / hn_len, surf_n.z / hn_len);
float vn = craft.vel.x * cliff_n.x + craft.vel.z * cliff_n.y;
if (vn < 0.0f) {
float push = (0.49f - surf_n.y) * 0.28f;
craft.curr_pose.pos.x += cliff_n.x * push;
craft.curr_pose.pos.z += cliff_n.y * push;
craft.vel.x -= (1.0f + kWallBounce) * vn * cliff_n.x;
craft.vel.z -= (1.0f + kWallBounce) * vn * cliff_n.y;
record_impact(-vn * 0.85f);
}
}
}
}
return hit;
}
CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input,
const assets::LevelData& level, float dt) {
CraftStepFeedback fb;
craft.prev_pose = craft.curr_pose;
if (craft.recovery_state != RecoveryState::Active) {
craft.vel = Vec3(0, 0, 0);
craft.scrape_intensity = 0.0f;
return fb;
}
const VehicleSpec& spec = kVehicleSpecs[std::clamp(craft.vehicle_idx, 0, 5)];
if (craft.damage_flash > 0.0f) craft.damage_flash = std::max(0.0f, craft.damage_flash - dt);
if (craft.minigun_cd > 0.0f) craft.minigun_cd = std::max(0.0f, craft.minigun_cd - dt);
if (craft.missile_cd > 0.0f) craft.missile_cd = std::max(0.0f, craft.missile_cd - dt);
if (craft.boost_cooldown > 0.0f) craft.boost_cooldown = std::max(0.0f, craft.boost_cooldown - dt);
if (craft.refuel_sound_cd > 0.0f) craft.refuel_sound_cd = std::max(0.0f, craft.refuel_sound_cd - dt);
// Steering & banking
float steer = std::clamp(input.steer, -1.0f, 1.0f);
float air_turn_mult = craft.airborne ? 1.45f : 1.0f;
float target_yaw_rate = -steer * spec.turn_rate * air_turn_mult;
craft.yaw_rate = lerp(craft.yaw_rate, target_yaw_rate, std::min(1.0f, dt * 11.0f));
float prev_yaw = craft.curr_pose.yaw;
craft.curr_pose.yaw = wrap_angle(craft.curr_pose.yaw + craft.yaw_rate * dt);
if (craft.airborne) {
craft.air_spin_accum += std::abs(wrap_angle(craft.curr_pose.yaw - prev_yaw));
}
Vec3 fwd(std::sin(craft.curr_pose.yaw), 0.0f, std::cos(craft.curr_pose.yaw));
Vec3 right(-fwd.z, 0.0f, fwd.x); // local -X is right side of craft
// Fuel consumption & boost handling
bool has_fuel = craft.fuel > 0.05f;
if (!has_fuel) {
fb.out_of_fuel = true;
}
bool want_boost = input.boost && has_fuel && craft.boost_cooldown <= 0.0f;
if (want_boost) {
craft.boost_timer = std::min(craft.boost_timer + dt, 2.5f);
fb.boosting = true;
} else if (craft.boost_timer > 0.0f) {
craft.boost_timer = std::max(0.0f, craft.boost_timer - dt * 2.0f);
}
float throttle = has_fuel ? std::clamp(input.throttle, 0.0f, 1.0f) : 0.0f;
float brake = std::clamp(input.brake, 0.0f, 1.0f);
float boost_mult = 1.0f + 0.14f * static_cast<float>(craft.booster_level - 1);
float max_spd = spec.top_speed + (fb.boosting ? spec.boost_bonus * boost_mult : 0.0f);
float accel = spec.accel * (fb.boosting ? 1.65f * boost_mult : 1.0f);
// Fuel burn proportional to throttle + boost
float burn = (throttle * 0.48f + (fb.boosting ? 2.4f : 0.0f) + 0.06f) * dt;
if (has_fuel) {
float used = std::min(craft.fuel, burn);
craft.fuel -= used;
craft.fuel_used += used;
}
// Forward/reverse thrust and hover lateral grip
if (!craft.airborne) {
craft.vel += fwd * (throttle * accel * dt);
if (brake > 0.0f) {
float fwd_spd = craft.vel.dot(fwd);
if (fwd_spd > 0.8f) {
craft.vel -= fwd * (brake * spec.reverse_accel * 1.6f * dt);
} else {
craft.vel -= fwd * (brake * spec.reverse_accel * dt);
}
}
// Lateral hover grip suppresses excessive sideways slide while retaining drift feel
float lat_v = craft.vel.dot(right);
float lat_damp = std::exp(-spec.lateral_grip * dt);
craft.vel -= right * (lat_v * (1.0f - lat_damp));
// Aerodynamic drag
float drag = (throttle > 0.05f || fb.boosting) ? 0.55f : 1.65f;
float hspd = craft.speed_horizontal();
if (hspd > max_spd) {
float excess = hspd - max_spd;
float scale = (hspd - std::min(excess, hspd * dt * 3.5f)) / std::max(hspd, 1e-4f);
craft.vel.x *= scale;
craft.vel.z *= scale;
} else {
float d = std::exp(-drag * dt);
craft.vel.x *= d;
craft.vel.z *= d;
}
} else {
// Gentle air control
craft.vel += fwd * (throttle * accel * 0.25f * dt);
}
// Sub-stepped integration + column/wall collision (prevents tunneling at top speed)
constexpr int kSubSteps = 2;
float sub_dt = dt / static_cast<float>(kSubSteps);
for (int s = 0; s < kSubSteps; ++s) {
craft.curr_pose.pos.x += craft.vel.x * sub_dt;
craft.curr_pose.pos.z += craft.vel.z * sub_dt;
// Vertical hover cushion vs gravity (supports elevated columns and overhead gantries)
float floor_y = 0.0f;
float ceil_y = 1e6f;
level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z,
craft.curr_pose.pos.y, floor_y, ceil_y);
float target_y = floor_y + spec.hover_offset;
if (craft.curr_pose.pos.y <= target_y + 0.08f && craft.vel.y <= 3.2f) {
// Landed or hovering smoothly
if (craft.airborne) {
float deg = rad_to_deg(craft.air_spin_accum);
if (deg >= 660.0f) fb.stunt_degrees = 720;
else if (deg >= 310.0f) fb.stunt_degrees = 360;
else if (deg >= 145.0f) fb.stunt_degrees = 180;
craft.airborne = false;
craft.airtime = 0.0f;
craft.air_spin_accum = 0.0f;
}
float y_err = target_y - craft.curr_pose.pos.y;
craft.vel.y += (y_err * 95.0f - craft.vel.y * 14.0f) * sub_dt;
craft.curr_pose.pos.y += craft.vel.y * sub_dt;
// Launch into air when cresting a hill fast!
float next_floor = 0.0f;
float next_ceil = 1e6f;
level.sample_surface_and_ceiling(
craft.curr_pose.pos.x + craft.vel.x * sub_dt * 2.0f,
craft.curr_pose.pos.z + craft.vel.z * sub_dt * 2.0f,
craft.curr_pose.pos.y, next_floor, next_ceil);
float ground_drop = (floor_y - next_floor) / std::max(sub_dt * 2.0f, 1e-4f);
if (ceil_y > 1e5f && ground_drop > 3.5f && craft.speed_horizontal() > 10.0f) {
craft.airborne = true;
craft.vel.y = std::max(craft.vel.y, 2.2f);
} else if (craft.curr_pose.pos.y < floor_y + 0.14f) {
craft.curr_pose.pos.y = floor_y + 0.14f;
if (craft.vel.y < 0.0f) craft.vel.y = 0.0f;
}
} else {
// Airborne ballistic motion
if (!craft.airborne) {
craft.airborne = true;
craft.air_spin_accum = 0.0f;
}
craft.airtime += sub_dt;
craft.vel.y -= kGravity * sub_dt;
craft.curr_pose.pos.y += craft.vel.y * sub_dt;
if (craft.curr_pose.pos.y <= target_y) {
float deg = rad_to_deg(craft.air_spin_accum);
if (deg >= 660.0f) fb.stunt_degrees = 720;
else if (deg >= 310.0f) fb.stunt_degrees = 360;
else if (deg >= 145.0f) fb.stunt_degrees = 180;
craft.curr_pose.pos.y = target_y;
craft.vel.y = std::max(0.0f, -craft.vel.y * 0.15f);
craft.airborne = false;
craft.airtime = 0.0f;
craft.air_spin_accum = 0.0f;
}
}
// Banked slope acceleration on tilted track surfaces
if (!craft.airborne) {
Vec3 sub_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z);
if (sub_n.y >= 0.49f && sub_n.y < 0.78f) {
craft.vel.x += sub_n.x * 5.0f * sub_dt;
craft.vel.z += sub_n.z * 5.0f * sub_dt;
}
}
float sub_impact = 0.0f;
bool sub_scraping = false;
if (resolve_world_collisions(craft, level, sub_impact, sub_scraping)) {
fb.collided_wall = true;
fb.impact_speed = std::max(fb.impact_speed, sub_impact);
fb.scraping |= sub_scraping;
}
}
// Smooth continuous scrape intensity for metallic wall-rubbing audio feedback
float target_scrape = fb.scraping ? std::clamp(craft.speed_horizontal() / spec.top_speed, 0.25f, 1.0f) : 0.0f;
craft.scrape_intensity = lerp(craft.scrape_intensity, target_scrape, std::min(1.0f, dt * 16.0f));
// Visual pitch & roll banking from terrain slope + steering
Vec3 surf_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z);
float slope_pitch = -std::asin(std::clamp(surf_n.dot(fwd), -0.7f, 0.7f));
float speed_ratio = std::clamp(craft.speed_horizontal() / spec.top_speed, 0.0f, 1.2f);
float target_roll = steer * 0.34f * speed_ratio;
float target_pitch = (craft.airborne ? std::clamp(-craft.vel.y * 0.04f, -0.35f, 0.35f) : slope_pitch) +
(fb.boosting ? -0.06f : 0.0f);
craft.curr_pose.pitch = lerp(craft.curr_pose.pitch, target_pitch, std::min(1.0f, dt * 10.0f));
craft.curr_pose.roll = lerp(craft.curr_pose.roll, target_roll, std::min(1.0f, dt * 10.0f));
return fb;
}
bool resolve_craft_pair_collision(CraftState& a, CraftState& b, float& out_rel_speed) {
if (a.recovery_state != RecoveryState::Active || b.recovery_state != RecoveryState::Active) {
return false;
}
Vec3 d = b.curr_pose.pos - a.curr_pose.pos;
if (std::abs(d.y) > 1.2f) return false;
const VehicleSpec& sa = kVehicleSpecs[std::clamp(a.vehicle_idx, 0, 5)];
const VehicleSpec& sb = kVehicleSpecs[std::clamp(b.vehicle_idx, 0, 5)];
float min_sep = sa.collision_radius + sb.collision_radius;
float dist_sq = d.x * d.x + d.z * d.z;
if (dist_sq >= min_sep * min_sep) return false;
float dist = std::sqrt(std::max(dist_sq, 1e-6f));
Vec2 n = (dist > 1e-4f) ? Vec2(d.x / dist, d.z / dist) : Vec2(1.0f, 0.0f);
float pen = (min_sep - dist) * 0.5f;
float ma = sa.mass;
float mb = sb.mass;
float inv_sum = 1.0f / (ma + mb);
a.curr_pose.pos.x -= n.x * pen * (mb * inv_sum) * 2.0f;
a.curr_pose.pos.z -= n.y * pen * (mb * inv_sum) * 2.0f;
b.curr_pose.pos.x += n.x * pen * (ma * inv_sum) * 2.0f;
b.curr_pose.pos.z += n.y * pen * (ma * inv_sum) * 2.0f;
float rvx = b.vel.x - a.vel.x;
float rvz = b.vel.z - a.vel.z;
float rel_n = rvx * n.x + rvz * n.y;
out_rel_speed = std::abs(rel_n);
if (rel_n < 0.0f) {
float j = -(1.28f) * rel_n * inv_sum;
a.vel.x -= j * mb * n.x;
a.vel.z -= j * mb * n.y;
b.vel.x += j * ma * n.x;
b.vel.z += j * ma * n.y;
}
return true;
}
CraftPose interpolate_pose(const CraftState& craft, float alpha) {
CraftPose out;
out.pos = lerp(craft.prev_pose.pos, craft.curr_pose.pos, alpha);
out.yaw = lerp_angle(craft.prev_pose.yaw, craft.curr_pose.yaw, alpha);
out.pitch = lerp(craft.prev_pose.pitch, craft.curr_pose.pitch, alpha);
out.roll = lerp(craft.prev_pose.roll, craft.curr_pose.roll, alpha);
return out;
}
} // namespace top_octane::sim
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#include "assets/level.hpp"
#include "core/math.hpp"
#include "input/input_manager.hpp"
#include "sim/vehicle_defs.hpp"
#include <string>
namespace top_octane::sim {
struct CraftPose {
Vec3 pos{0.0f, 0.0f, 0.0f};
float yaw = 0.0f;
float pitch = 0.0f;
float roll = 0.0f;
};
enum class RecoveryState {
Active = 0,
CallingRepair,
AwaitingRepair,
Repairing,
Destroyed,
};
struct CraftState {
int id = 0;
bool is_human = false;
int player_index = -1; // 0 = P1, 1 = P2, -1 = AI
int vehicle_idx = 0;
int team_idx = 7;
std::string pilot_name;
CraftPose prev_pose{};
CraftPose curr_pose{};
Vec3 vel{0.0f, 0.0f, 0.0f};
float yaw_rate = 0.0f;
bool airborne = false;
float airtime = 0.0f;
float air_spin_accum = 0.0f;
// Resources & upgrades
float fuel = 100.0f;
float max_fuel = 100.0f;
float shield = 100.0f;
float max_shield = 100.0f;
float ammo = 100.0f;
float max_ammo = 100.0f;
int minigun_level = 1;
int missile_level = 1;
int booster_level = 1;
// Timers & weapons
float minigun_cd = 0.0f;
float missile_cd = 0.0f;
float boost_timer = 0.0f;
float boost_cooldown = 0.0f;
float damage_flash = 0.0f;
int lock_target_id = -1;
float lock_progress = 0.0f;
float scrape_intensity = 0.0f;
float refuel_sound_cd = 0.0f;
bool autopilot = false;
// Recovery / repair
RecoveryState recovery_state = RecoveryState::Active;
float recovery_timer = 0.0f;
Vec3 recovery_pos{0.0f, 0.0f, 0.0f};
// Race / Deathmatch progression
int lap = 1;
int next_checkpoint = 1;
int checkpoints_passed = 0;
int current_wp = 0;
bool wrong_way = false;
bool finished = false;
float race_time = 0.0f;
float current_lap_time = 0.0f;
float best_lap_time = 0.0f;
int placement = 1;
int kills = 0;
int deaths = 0;
float fuel_used = 0.0f;
float armour_used = 0.0f;
int shots_fired = 0;
int shots_hit = 0;
std::string killed_by;
// AI state
int ai_target_wp = 0;
float ai_fire_delay = 0.0f;
bool ai_seeking_pit = false;
int ai_pit_pad_idx = -1;
float speed_horizontal() const {
return std::sqrt(vel.x * vel.x + vel.z * vel.z);
}
Vec3 forward_dir() const {
return Vec3(std::sin(curr_pose.yaw), 0.0f, std::cos(curr_pose.yaw));
}
};
struct CraftStepFeedback {
bool collided_wall = false;
float impact_speed = 0.0f;
bool scraping = false;
bool boosting = false;
int stunt_degrees = 0; // 180, 360, or 720 on landing
bool out_of_fuel = false;
};
// Pure deterministic 60 Hz hover physics step for one active craft
CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input,
const assets::LevelData& level, float dt);
// Resolves world boundary, column AABB, ceiling, and cliff collisions for one active craft
bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level,
float& out_impact_speed, bool& out_scraping);
// Resolves sphere-sphere bounce between two active crafts
bool resolve_craft_pair_collision(CraftState& a, CraftState& b, float& out_rel_speed);
// Interpolates craft pose for smooth rendering at arbitrary refresh rate
CraftPose interpolate_pose(const CraftState& craft, float alpha);
} // namespace top_octane::sim
+547
View File
@@ -0,0 +1,547 @@
#include "sim/race_sim.hpp"
#include "sim/ai_driver.hpp"
#include "sim/combat.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
namespace top_octane::sim {
namespace {
bool segments_intersect_or_near(Vec2 p0, Vec2 p1, Vec2 g0, Vec2 g1, float margin = 2.5f) {
// Check if craft crossed near checkpoint gate line (segment g0..g1 or center proximity)
Vec2 mid = (g0 + g1) * 0.5f;
float gate_half = std::max((g1 - g0).len() * 0.5f, 3.0f) + margin;
if ((p1 - mid).len_sq() > gate_half * gate_half && (p0 - mid).len_sq() > gate_half * gate_half) {
return false;
}
Vec2 seg = g1 - g0;
if (seg.len_sq() < 0.25f) {
return (p1 - mid).len() <= 3.5f;
}
Vec2 n(-seg.y, seg.x);
float d0 = (p0 - g0).dot(n);
float d1 = (p1 - g0).dot(n);
if ((d0 <= 0.0f && d1 >= 0.0f) || (d0 >= 0.0f && d1 <= 0.0f)) {
float t = (p1 - g0).dot(seg) / seg.len_sq();
return t >= -0.35f && t <= 1.35f;
}
return false;
}
} // namespace
bool RaceSim::start_race(const assets::LevelData& level, const RaceSetup& setup,
const CloneRecording* existing_clone) {
level_ = level;
setup_ = setup;
crafts_.clear();
projectiles_.clear();
pickups_.clear();
props_.clear();
particles_.clear();
events_.clear();
countdown_timer_ = 3.0f;
last_countdown_int_ = 4;
elapsed_time_ = 0.0f;
race_over_ = false;
winner_id_ = -1;
terrain_dirty_ = false;
// Populate pickups (type 5) & props (type 3)
for (const auto& e : level_.pickups) {
PickupItem p;
p.entity_id = e.id;
p.subtype = e.subtype;
float tx = e.tile_x() + 0.5f;
float tz = e.tile_z() + 0.5f;
p.pos = Vec3(tx, level_.sample_height_world(tx, tz) + 0.45f, tz);
pickups_.push_back(p);
}
for (const auto& e : level_.props) {
PropObject pr;
pr.entity_id = e.id;
pr.subtype = e.subtype;
if (e.subtype == 3) pr.model_key = "BAREL0-0";
else pr.model_key = "CONE0-0";
float tx = e.tile_x() + 0.5f;
float tz = e.tile_z() + 0.5f;
pr.pos = Vec3(tx, level_.sample_height_world(tx, tz) + 0.25f, tz);
props_.push_back(pr);
}
trigger_fired_.assign(level_.triggers.size(), false);
int total_racers = 1;
if (setup_.mode == GameMode::SplitScreen) {
total_racers = 2 + std::clamp(setup_.num_ai, 0, 6);
} else if (setup_.mode == GameMode::CloneRace) {
total_racers = 1;
} else {
total_racers = 1 + std::clamp(setup_.num_ai, 0, 7);
}
std::vector<CraftPose> grid;
compute_start_grid(total_racers, grid);
auto make_craft = [&](int id, bool human, int p_idx, int veh, int team,
const std::string& name, const CraftPose& pose) {
const VehicleSpec& sp = kVehicleSpecs[std::clamp(veh, 0, 5)];
CraftState c;
c.id = id;
c.is_human = human;
c.player_index = p_idx;
c.vehicle_idx = veh;
c.team_idx = team;
c.pilot_name = name;
c.prev_pose = pose;
c.curr_pose = pose;
c.fuel = c.max_fuel = sp.max_fuel;
c.shield = c.max_shield = sp.max_shield;
c.ammo = c.max_ammo = sp.max_ammo;
c.placement = id + 1;
c.ai_target_wp = level_.main_waypoints.size() > 1 ? 1 : 0;
return c;
};
crafts_.push_back(make_craft(0, true, 0, setup_.p1_vehicle, setup_.p1_team,
setup_.p1_name.empty() ? "PLAYER" : setup_.p1_name, grid[0]));
int next_id = 1;
if (setup_.mode == GameMode::SplitScreen) {
crafts_.push_back(make_craft(1, true, 1, setup_.p2_vehicle, setup_.p2_team,
setup_.p2_name.empty() ? "PLAYER 2" : setup_.p2_name, grid[1]));
next_id = 2;
}
for (int i = next_id; i < total_racers; ++i) {
int ai_idx = i - next_id;
int team = (ai_idx == setup_.p1_team) ? ((ai_idx + 1) % 8) : (ai_idx % 8);
int veh = (ai_idx * 5 + setup_.track_number) % 6;
crafts_.push_back(make_craft(i, false, -1, veh, team, kPilotNames[ai_idx % 8], grid[i]));
}
recording_ = CloneRecording{};
recording_.track_number = setup_.track_number;
recording_.vehicle_idx = setup_.p1_vehicle;
recording_.team_idx = setup_.p1_team;
clone_active_ = (setup_.mode == GameMode::CloneRace && existing_clone != nullptr &&
!existing_clone->frames.empty() &&
existing_clone->track_number == setup_.track_number);
if (clone_active_) {
playback_clone_ = *existing_clone;
} else {
playback_clone_ = CloneRecording{};
}
clone_tick_ = 0;
return true;
}
void RaceSim::compute_start_grid(int count, std::vector<CraftPose>& out_poses) const {
out_poses.resize(count);
Vec2 fwd(0.0f, -1.0f);
Vec2 origin(12.0f, 82.0f);
if (!level_.checkpoints.empty()) {
origin = Vec2(level_.checkpoints[0].cx, level_.checkpoints[0].cz);
fwd = level_.checkpoints[0].dir;
}
if (level_.main_waypoints.size() >= 2) {
Vec2 wp_prev(level_.main_waypoints.back().x, level_.main_waypoints.back().z);
Vec2 wp_next(level_.main_waypoints[0].x, level_.main_waypoints[0].z);
Vec2 seg = wp_next - wp_prev;
float seg_len_sq = seg.len_sq();
if (seg_len_sq > 0.1f) {
fwd = seg * (1.0f / std::sqrt(seg_len_sq));
float t = std::clamp((origin - wp_prev).dot(seg) / seg_len_sq, 0.0f, 1.0f);
origin = wp_prev + seg * t;
}
}
Vec2 right(-fwd.y, fwd.x);
float yaw = std::atan2(fwd.x, fwd.y);
auto is_slot_clear = [&](float px, float pz, int placed_count) -> bool {
if (px < 2.0f || px > assets::kMapWidth - 3.0f ||
pz < 2.0f || pz > assets::kMapHeight - 3.0f) {
return false;
}
float py = level_.sample_height_world(px, pz) + 0.30f;
int cx = static_cast<int>(std::floor(px));
int cz = static_cast<int>(std::floor(pz));
constexpr float kClearRadius = 0.62f;
for (int nz = cz - 1; nz <= cz + 1; ++nz) {
for (int nx = cx - 1; nx <= cx + 1; ++nx) {
if (!level_.is_cell_solid_at_y(nx, nz, py)) continue;
float clx = std::clamp(px, static_cast<float>(nx), static_cast<float>(nx + 1));
float clz = std::clamp(pz, static_cast<float>(nz), static_cast<float>(nz + 1));
float dx = px - clx;
float dz = pz - clz;
if (dx * dx + dz * dz < kClearRadius * kClearRadius) {
return false;
}
}
}
for (int k = 0; k < placed_count; ++k) {
float dx = px - out_poses[k].pos.x;
float dz = pz - out_poses[k].pos.z;
if (dx * dx + dz * dz < 1.30f * 1.30f) {
return false;
}
}
return true;
};
for (int i = 0; i < count; ++i) {
int row = i / 2;
int col = i % 2;
float base_back = 2.0f + static_cast<float>(row) * 1.85f;
float pref_lat = (col == 0 ? -0.85f : 0.85f);
Vec2 chosen = origin - fwd * base_back + right * pref_lat;
bool found = false;
// 1. Ideal 2-wide slot, then slight inward squeeze, then safe stagger along road centerline
const float lat_tries[3] = {pref_lat, pref_lat * 0.62f, 0.0f};
for (int step = 0; step < 10 && !found; ++step) {
float back = base_back + static_cast<float>(step) * 1.35f;
for (float lat : lat_tries) {
if (step == 0 && lat == 0.0f && i > 0) continue; // avoid squeezing same-row partner
Vec2 cand = origin - fwd * back + right * lat;
if (is_slot_clear(cand.x, cand.y, i)) {
chosen = cand;
found = true;
break;
}
}
}
if (!found) {
for (int step = 0; step < 12 && !found; ++step) {
Vec2 cand = origin - fwd * (base_back + static_cast<float>(step) * 1.35f);
if (is_slot_clear(cand.x, cand.y, i)) {
chosen = cand;
found = true;
}
}
}
float y = level_.sample_height_world(chosen.x, chosen.y) + 0.30f;
CraftPose cp;
cp.pos = Vec3(chosen.x, y, chosen.y);
cp.yaw = yaw;
out_poses[i] = cp;
}
}
void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float dt) {
// Countdown handling
if (countdown_timer_ > 0.0f) {
countdown_timer_ = std::max(0.0f, countdown_timer_ - dt);
int c_int = static_cast<int>(std::ceil(countdown_timer_));
if (c_int != last_countdown_int_) {
last_countdown_int_ = c_int;
if (c_int > 0) {
events_.push_back({SimSoundCue::StartBeep, Vec3(0, 0, 0), -1,
std::to_string(c_int), 0.0f});
} else {
events_.push_back({SimSoundCue::StartGo, Vec3(0, 0, 0), -1, "GO!", 0.2f});
}
}
// Keep previous poses synced during countdown
for (auto& c : crafts_) {
c.prev_pose = c.curr_pose;
}
return;
}
elapsed_time_ += dt;
std::vector<CraftInput> inputs(crafts_.size());
for (size_t i = 0; i < crafts_.size(); ++i) {
CraftState& c = crafts_[i];
CraftInput in;
if (c.is_human) {
in = (c.player_index == 1) ? p2_input : p1_input;
if (in.toggle_autopilot_pressed) {
c.autopilot = !c.autopilot;
events_.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index,
c.autopilot ? "AUTO PILOT ON" : "AUTO PILOT OFF", 0.0f});
}
if (c.autopilot) {
CraftInput ai_in = compute_ai_input(c, level_, crafts_, setup_.difficulty);
in.steer = ai_in.steer;
in.throttle = ai_in.throttle;
in.brake = ai_in.brake;
}
} else {
in = compute_ai_input(c, level_, crafts_, setup_.difficulty);
}
inputs[i] = in;
float prev_boost_timer = c.boost_timer;
CraftStepFeedback fb = step_craft_physics(c, in, level_, dt);
if (fb.collided_wall && fb.impact_speed > 3.8f) {
events_.push_back({SimSoundCue::Impact, c.curr_pose.pos, c.player_index, "",
std::clamp(fb.impact_speed / 16.0f, 0.1f, 0.9f)});
}
if (prev_boost_timer <= 0.01f && c.boost_timer > 0.0f && fb.boosting) {
events_.push_back({SimSoundCue::Boost, c.curr_pose.pos, c.player_index, "", 0.35f});
}
if (fb.boosting && (static_cast<int>(elapsed_time_ * 12.0f) % 4 == 0)) {
Vec3 back = c.curr_pose.pos - c.forward_dir() * 0.65f;
particles_.push_back({back, -c.forward_dir() * 2.5f + Vec3(0, 0.4f, 0),
0.38f, Vec4(0.35f, 0.75f, 1.0f, 0.95f), 0.18f, 0.18f});
}
if (fb.stunt_degrees > 0) {
SimSoundCue sc = (fb.stunt_degrees >= 720) ? SimSoundCue::Stunt720 :
(fb.stunt_degrees >= 360) ? SimSoundCue::Stunt360 : SimSoundCue::Stunt180;
float bonus = (fb.stunt_degrees >= 720) ? 45.0f : (fb.stunt_degrees >= 360 ? 25.0f : 12.0f);
c.fuel = std::min(c.max_fuel, c.fuel + bonus);
c.shield = std::min(c.max_shield, c.shield + bonus * 0.5f);
events_.push_back({sc, c.curr_pose.pos, c.player_index,
std::to_string(fb.stunt_degrees) + "!", 0.4f});
}
if (!c.finished) {
c.race_time += dt;
c.current_lap_time += dt;
}
update_checkpoints_and_laps(c);
update_recharge_pads(c, dt);
update_triggers(c);
}
// Combat, projectiles, pickups, props, and recovery craft
step_combat_and_world(setup_, level_, crafts_, inputs, projectiles_, pickups_, props_,
particles_, events_, race_over_, winner_id_, dt);
// Multi-iteration craft-to-craft + world re-projection solver so squeezed crafts never clip walls
for (int iter = 0; iter < 2; ++iter) {
for (size_t i = 0; i < crafts_.size(); ++i) {
for (size_t j = i + 1; j < crafts_.size(); ++j) {
float rel = 0.0f;
if (resolve_craft_pair_collision(crafts_[i], crafts_[j], rel) && iter == 0 && rel > 3.5f) {
events_.push_back({SimSoundCue::Impact, crafts_[i].curr_pose.pos,
crafts_[i].is_human ? crafts_[i].player_index :
(crafts_[j].is_human ? crafts_[j].player_index : -1),
"", std::clamp(rel / 15.0f, 0.15f, 0.8f)});
}
}
}
for (size_t i = 0; i < crafts_.size(); ++i) {
float dummy_imp = 0.0f;
bool dummy_scr = false;
resolve_world_collisions(crafts_[i], level_, dummy_imp, dummy_scr);
}
}
// Record P1 ghost frames (cap at 5 minutes = 18000 frames)
if (!crafts_.empty() && recording_.frames.size() < 18000) {
recording_.frames.push_back(crafts_[0].curr_pose);
if (crafts_[0].finished && recording_.best_race_time > crafts_[0].race_time) {
recording_.best_race_time = crafts_[0].race_time;
}
}
if (clone_active_) {
++clone_tick_;
}
update_standings();
update_particles(dt);
}
void RaceSim::update_checkpoints_and_laps(CraftState& c) {
if (level_.checkpoints.empty() || c.finished) return;
int num_cps = static_cast<int>(level_.checkpoints.size());
Vec2 p0(c.prev_pose.pos.x, c.prev_pose.pos.z);
Vec2 p1(c.curr_pose.pos.x, c.curr_pose.pos.z);
int expected = c.next_checkpoint % num_cps;
const auto& gate = level_.checkpoints[expected];
if (segments_intersect_or_near(p0, p1, Vec2(gate.x0, gate.z0), Vec2(gate.x1, gate.z1))) {
++c.checkpoints_passed;
c.next_checkpoint = (expected + 1) % num_cps;
c.wrong_way = false;
if (expected == 0) {
if (c.best_lap_time <= 0.0f || c.current_lap_time < c.best_lap_time) {
c.best_lap_time = c.current_lap_time;
}
c.current_lap_time = 0.0f;
if (c.lap >= setup_.total_laps && setup_.mode != GameMode::DeathMatch) {
c.finished = true;
if (winner_id_ < 0) {
winner_id_ = c.id;
if (c.is_human) race_over_ = true;
}
} else {
++c.lap;
if (c.lap == setup_.total_laps && c.is_human) {
events_.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index, "FINAL LAP", 0.0f});
}
}
}
}
// Wrong way detection via nearest main waypoint forward dot product
if (level_.main_waypoints.size() >= 2 && c.speed_horizontal() > 3.0f) {
size_t best_wp = 0;
float best_d2 = 1e18f;
for (size_t i = 0; i < level_.main_waypoints.size(); ++i) {
float dx = level_.main_waypoints[i].x - c.curr_pose.pos.x;
float dz = level_.main_waypoints[i].z - c.curr_pose.pos.z;
float d2 = dx * dx + dz * dz;
if (d2 < best_d2) {
best_d2 = d2;
best_wp = i;
}
}
c.current_wp = static_cast<int>(best_wp);
const auto& w0 = level_.main_waypoints[best_wp];
const auto& w1 = level_.main_waypoints[(best_wp + 1) % level_.main_waypoints.size()];
Vec2 track_dir = Vec2(w1.x - w0.x, w1.z - w0.z).normalized();
Vec2 vel_dir = Vec2(c.vel.x, c.vel.z).normalized();
c.wrong_way = (track_dir.dot(vel_dir) < -0.55f);
}
}
void RaceSim::update_recharge_pads(CraftState& c, float dt) {
if (c.recovery_state != RecoveryState::Active) return;
for (size_t i = 0; i < level_.pads.size(); ++i) {
const auto& pad = level_.pads[i];
float dx = c.curr_pose.pos.x - (pad.tile_x() + 0.5f);
float dz = c.curr_pose.pos.z - (pad.tile_z() + 0.5f);
if (dx * dx + dz * dz < 6.25f) {
// Recharge fuel, shield & ammo smoothly over track pads
bool recharged = false;
if (c.fuel < c.max_fuel) {
c.fuel = std::min(c.max_fuel, c.fuel + 38.0f * dt);
recharged = true;
}
if (c.shield < c.max_shield) {
c.shield = std::min(c.max_shield, c.shield + 32.0f * dt);
recharged = true;
}
if (c.ammo < c.max_ammo) {
c.ammo = std::min(c.max_ammo, c.ammo + 35.0f * dt);
recharged = true;
}
if (recharged && c.is_human && c.refuel_sound_cd <= 0.0f) {
c.refuel_sound_cd = 0.45f;
events_.push_back({SimSoundCue::Refuel, c.curr_pose.pos, c.player_index, "", 0.0f});
}
break;
}
}
}
void RaceSim::update_triggers(CraftState& c) {
for (size_t i = 0; i < level_.triggers.size(); ++i) {
if (trigger_fired_[i]) continue;
const auto& tr = level_.triggers[i];
float dx = c.curr_pose.pos.x - (tr.tile_x() + 0.5f);
float dz = c.curr_pose.pos.z - (tr.tile_z() + 0.5f);
if (dx * dx + dz * dz < 4.0f) {
trigger_fired_[i] = true;
// Subtle dynamic terrain pulse around trigger zone so morph events visibly deform track!
int cx = static_cast<int>(tr.tile_x());
int cz = static_cast<int>(tr.tile_z());
for (int z = std::max(1, cz - 2); z <= std::min(assets::kMapHeight - 2, cz + 2); ++z) {
for (int x = std::max(1, cx - 2); x <= std::min(assets::kMapWidth - 2, cx + 2); ++x) {
auto& cell = level_.cell_mut(x, z);
cell.height = static_cast<uint16_t>(std::min<int>(cell.height + 160, 4080));
}
}
terrain_dirty_ = true;
dirty_x0_ = std::max(0, cx - 3);
dirty_z0_ = std::max(0, cz - 3);
dirty_x1_ = std::min(assets::kMapWidth - 2, cx + 3);
dirty_z1_ = std::min(assets::kMapHeight - 2, cz + 3);
events_.push_back({SimSoundCue::SwitchTrigger, c.curr_pose.pos, c.player_index,
"SECTOR MORPHING", 0.35f});
}
}
}
void RaceSim::update_standings() {
std::vector<size_t> order(crafts_.size());
for (size_t i = 0; i < crafts_.size(); ++i) order[i] = i;
std::sort(order.begin(), order.end(), [&](size_t ia, size_t ib) {
const CraftState& a = crafts_[ia];
const CraftState& b = crafts_[ib];
if (setup_.mode == GameMode::DeathMatch) {
if (a.kills != b.kills) return a.kills > b.kills;
return a.deaths < b.deaths;
}
if (a.finished != b.finished) return a.finished;
if (a.finished && b.finished) return a.race_time < b.race_time;
if (a.checkpoints_passed != b.checkpoints_passed) {
return a.checkpoints_passed > b.checkpoints_passed;
}
// Tie-break by proximity to next checkpoint
if (!level_.checkpoints.empty()) {
const auto& ga = level_.checkpoints[a.next_checkpoint % level_.checkpoints.size()];
const auto& gb = level_.checkpoints[b.next_checkpoint % level_.checkpoints.size()];
float da = (a.curr_pose.pos.x - ga.cx) * (a.curr_pose.pos.x - ga.cx) +
(a.curr_pose.pos.z - ga.cz) * (a.curr_pose.pos.z - ga.cz);
float db = (b.curr_pose.pos.x - gb.cx) * (b.curr_pose.pos.x - gb.cx) +
(b.curr_pose.pos.z - gb.cz) * (b.curr_pose.pos.z - gb.cz);
return da < db;
}
return ia < ib;
});
for (size_t rank = 0; rank < order.size(); ++rank) {
crafts_[order[rank]].placement = static_cast<int>(rank + 1);
}
// In 1P modes, end race when all human players finish
bool all_humans_done = true;
for (const auto& c : crafts_) {
if (c.is_human && !c.finished) all_humans_done = false;
}
if (all_humans_done && !crafts_.empty()) {
race_over_ = true;
}
}
void RaceSim::update_particles(float dt) {
for (auto& p : particles_) {
p.pos += p.vel * dt;
p.life -= dt;
p.color.w = std::clamp(p.life / std::max(p.max_life, 0.01f), 0.0f, 1.0f);
}
particles_.erase(
std::remove_if(particles_.begin(), particles_.end(),
[](const ParticleBurst& p) { return p.life <= 0.0f; }),
particles_.end());
}
CraftPose RaceSim::interpolated_clone_pose(float alpha) const {
if (!clone_active_ || playback_clone_.frames.empty()) return CraftPose{};
size_t i1 = std::min(clone_tick_, playback_clone_.frames.size() - 1);
size_t i0 = (i1 > 0) ? (i1 - 1) : 0;
const CraftPose& a = playback_clone_.frames[i0];
const CraftPose& b = playback_clone_.frames[i1];
CraftPose r;
r.pos = lerp(a.pos, b.pos, alpha);
r.yaw = lerp_angle(a.yaw, b.yaw, alpha);
r.pitch = lerp(a.pitch, b.pitch, alpha);
r.roll = lerp(a.roll, b.roll, alpha);
return r;
}
bool RaceSim::consume_terrain_dirty(int& x0, int& z0, int& x1, int& z1) {
if (!terrain_dirty_) return false;
x0 = dirty_x0_;
z0 = dirty_z0_;
x1 = dirty_x1_;
z1 = dirty_z1_;
terrain_dirty_ = false;
return true;
}
} // namespace top_octane::sim
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include "assets/level.hpp"
#include "core/math.hpp"
#include "input/input_manager.hpp"
#include "sim/physics.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace top_octane::sim {
enum class GameMode {
SingleRace = 0,
DeathMatch = 1,
CloneRace = 2,
Championship = 3,
SplitScreen = 4,
};
enum class SimSoundCue {
None = 0,
StartBeep,
StartGo,
MinigunShot,
MissileLaunch,
Explosion,
Impact,
Scrape,
Boost,
Pickup,
Powerup,
Refuel,
LockOn,
Warning,
Stunt180,
Stunt360,
Stunt720,
SwitchTrigger,
};
struct SimEvent {
SimSoundCue sound = SimSoundCue::None;
Vec3 pos{0, 0, 0};
int target_player = -1; // -1 = global, 0 = P1, 1 = P2
std::string banner_text;
float rumble_intensity = 0.0f;
};
struct Projectile {
bool active = false;
bool is_missile = false;
int owner_id = -1;
int target_id = -1;
Vec3 pos{0, 0, 0};
Vec3 vel{0, 0, 0};
float yaw = 0.0f;
float damage = 10.0f;
float life = 2.0f;
};
struct PickupItem {
uint16_t entity_id = 0;
uint8_t subtype = 0;
Vec3 pos{0, 0, 0};
bool active = true;
float respawn_timer = 0.0f;
};
struct PropObject {
uint16_t entity_id = 0;
uint8_t subtype = 0;
std::string model_key;
Vec3 pos{0, 0, 0};
float yaw = 0.0f;
float hp = 25.0f;
bool alive = true;
float respawn_timer = 0.0f;
};
struct ParticleBurst {
Vec3 pos{0, 0, 0};
Vec3 vel{0, 0, 0};
float size = 0.4f;
Vec4 color{1.0f, 0.7f, 0.2f, 1.0f};
float life = 0.5f;
float max_life = 0.5f;
};
struct CloneRecording {
int track_number = 1;
int vehicle_idx = 0;
int team_idx = 7;
float best_race_time = 1e9f;
std::vector<CraftPose> frames; // 60 Hz sampled poses
};
struct RaceSetup {
GameMode mode = GameMode::SingleRace;
int track_number = 1; // 1..6
int total_laps = 3;
int difficulty = 1; // 0=Easy, 1=Medium, 2=Hard
int num_ai = 7; // 0..7
int p1_vehicle = 0;
int p1_team = 7;
std::string p1_name = "PLAYER";
int p2_vehicle = 3;
int p2_team = 1;
std::string p2_name = "PLAYER 2";
int deathmatch_kill_limit = 5;
};
class RaceSim {
public:
bool start_race(const assets::LevelData& level, const RaceSetup& setup,
const CloneRecording* existing_clone = nullptr);
// Advances 1 fixed 60 Hz tick
void step(const CraftInput& p1_input, const CraftInput& p2_input, float dt);
const RaceSetup& setup() const { return setup_; }
const assets::LevelData& level() const { return level_; }
const std::vector<CraftState>& crafts() const { return crafts_; }
std::vector<CraftState>& crafts_mut() { return crafts_; }
const std::vector<Projectile>& projectiles() const { return projectiles_; }
const std::vector<PickupItem>& pickups() const { return pickups_; }
const std::vector<PropObject>& props() const { return props_; }
const std::vector<ParticleBurst>& particles() const { return particles_; }
const std::vector<SimEvent>& events() const { return events_; }
void clear_events() { events_.clear(); }
bool countdown_active() const { return countdown_timer_ > 0.0f; }
float countdown_timer() const { return countdown_timer_; }
bool race_finished() const { return race_over_; }
int winner_id() const { return winner_id_; }
bool has_clone_ghost() const { return clone_active_; }
CraftPose interpolated_clone_pose(float alpha) const;
const CloneRecording& current_recording() const { return recording_; }
// Checks if morph triggers fired and changed terrain heights
bool consume_terrain_dirty(int& x0, int& z0, int& x1, int& z1);
private:
void compute_start_grid(int count, std::vector<CraftPose>& out_poses) const;
void update_checkpoints_and_laps(CraftState& c);
void update_recharge_pads(CraftState& c, float dt);
void update_triggers(CraftState& c);
void update_standings();
void update_particles(float dt);
RaceSetup setup_{};
assets::LevelData level_{};
std::vector<CraftState> crafts_;
std::vector<Projectile> projectiles_;
std::vector<PickupItem> pickups_;
std::vector<PropObject> props_;
std::vector<ParticleBurst> particles_;
std::vector<SimEvent> events_;
float countdown_timer_ = 3.0f;
int last_countdown_int_ = 4;
float elapsed_time_ = 0.0f;
bool race_over_ = false;
int winner_id_ = -1;
// Trigger/morph tracking
std::vector<bool> trigger_fired_;
bool terrain_dirty_ = false;
int dirty_x0_ = 0, dirty_z0_ = 0, dirty_x1_ = 0, dirty_z1_ = 0;
// Clone race recording & playback
CloneRecording recording_;
CloneRecording playback_clone_;
bool clone_active_ = false;
size_t clone_tick_ = 0;
};
} // namespace top_octane::sim
+110
View File
@@ -0,0 +1,110 @@
#pragma once
#include <array>
#include <string>
namespace top_octane::sim {
struct VehicleSpec {
const char* name;
const char* model_prefix; // CAR0-, TANK0-, JUGGA0-, JET0-, BIKE0-, SKIM0-
// Display bars (1..10)
int stat_weight;
int stat_armour;
int stat_speed;
int stat_firepower;
// Tuned 60 Hz simulation parameters (world units = tiles)
float mass;
float top_speed; // tiles/sec
float accel; // tiles/sec^2
float reverse_accel;
float boost_bonus; // additional speed while boosting
float turn_rate; // rad/sec
float lateral_grip; // higher = less hover drift
float max_fuel;
float max_shield;
float max_ammo;
float minigun_damage;
float missile_damage;
float visual_scale; // uniform render scale so meshes match world track width
float collision_radius; // XZ circle collider radius (tiles)
float hover_offset; // vertical center offset above road surface
};
inline constexpr std::array<VehicleSpec, 6> kVehicleSpecs = {{
// 0: KD-1 Speeder (CAR) - Well-rounded standard hovercar
{"KD-1 SPEEDER", "CAR0-", 5, 5, 7, 5, 1.00f, 18.5f, 19.0f, 10.0f, 7.5f, 2.55f, 4.6f, 100.0f, 100.0f, 100.0f, 9.0f, 42.0f, 0.72f, 0.48f, 0.28f},
// 1: Beserker (TANK) - Heavy assault craft
{"BESERKER", "TANK0-", 8, 8, 5, 8, 1.35f, 16.5f, 16.0f, 9.0f, 6.5f, 2.15f, 5.0f, 110.0f, 135.0f, 125.0f, 12.0f, 54.0f, 0.36f, 0.56f, 0.26f},
// 2: Jugga (JUGGA) - Maximum armour & firepower juggernaut
{"JUGGA", "JUGGA0-",10,10, 4,10, 1.65f, 15.2f, 14.2f, 8.0f, 6.0f, 1.90f, 5.2f, 125.0f, 165.0f, 150.0f, 14.0f, 62.0f, 0.42f, 0.60f, 0.28f},
// 3: Vampyr (JET) - Top speed interceptor
{"VAMPYR", "JET0-", 4, 4,10, 7, 0.85f, 21.0f, 21.5f, 11.0f, 8.8f, 2.75f, 4.1f, 95.0f, 90.0f, 110.0f, 11.0f, 48.0f, 0.44f, 0.50f, 0.30f},
// 4: Outrider (BIKE) - Ultra-nimble light hoverbike
{"OUTRIDER", "BIKE0-", 2, 3, 9, 4, 0.70f, 19.8f, 23.0f, 12.0f, 8.2f, 3.25f, 4.8f, 90.0f, 80.0f, 90.0f, 8.0f, 38.0f, 0.68f, 0.42f, 0.22f},
// 5: Flexiwing (SKIM) - Balanced high-grip glider
{"FLEXIWING", "SKIM0-", 6, 6, 8, 6, 1.05f, 19.0f, 19.8f, 10.5f, 7.6f, 2.70f, 5.6f, 105.0f, 115.0f, 105.0f, 10.0f, 45.0f, 0.36f, 0.52f, 0.26f},
}};
inline constexpr std::array<const char*, 8> kTeamNames = {{
"MAD MEDICINE",
"ASSASSINS",
"GOREHOUNDS",
"FOO FIGHTERS",
"DETHFEST",
"FIRE PHREAKS",
"STORM RIDERS",
"BULLFROG",
}};
inline constexpr std::array<const char*, 8> kPilotNames = {{
"SCOPER",
"BARNSY",
"SHUNTLY",
"COPSE",
"MANNY",
"MCLALIN",
"MAD",
"ATROW",
}};
inline constexpr std::array<const char*, 20> kDriverRatings = {{
"SMEAR",
"SCRAP",
"VICTIM",
"CANYON KISSER",
"BACK MARKER",
"TARGET PRACTICE",
"ENDANGERED SPECIES",
"TOO SLOW",
"MEDIOCRE",
"UPWARDLY MOBILE",
"DUST DEVIL",
"ANTISOCIAL",
"TAILGATER",
"DANGEROUS",
"WRECKER",
"DEADLY",
"DEMON",
"OUTTA CONTROL",
"HARDWIRED",
"IMMORTAL",
}};
inline std::string model_key_for(int vehicle_idx, int team_idx) {
int v = (vehicle_idx < 0 || vehicle_idx >= 6) ? 0 : vehicle_idx;
int t = (team_idx < 0 || team_idx >= 8) ? 7 : team_idx;
return std::string(kVehicleSpecs[v].model_prefix) + std::to_string(t);
}
inline const char* rating_for_score(int rating_points) {
int idx = rating_points / 50;
if (idx < 0) idx = 0;
if (idx >= static_cast<int>(kDriverRatings.size())) {
idx = static_cast<int>(kDriverRatings.size()) - 1;
}
return kDriverRatings[idx];
}
} // namespace top_octane::sim