sdk de8fa40: B-spline loop window, cubic curves, degree-0 first-knot>t. ActorInstance passes the motion's loop flag to SetAnimationLoop so looping motions sample across the seam instead of clamping to the end knots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1247 lines
56 KiB
C++
1247 lines
56 KiB
C++
#include "Gr2ModelRenderer.h"
|
|
#include "TerrainHeightmap.h"
|
|
#include "src/eter_resource/ResourceManager.h"
|
|
#include "src/eter_resource/dxt.h"
|
|
#include <cmath>
|
|
#include <algorithm>
|
|
#include <iostream>
|
|
#include <filesystem>
|
|
#include <cctype>
|
|
#include <cstring>
|
|
|
|
namespace ava2 {
|
|
|
|
namespace {
|
|
bool hardwareSkinningEnabled=false;
|
|
|
|
inline void MultiplyMat4(const float* a, const float* b, float* out) {
|
|
float r[16];
|
|
for (int i = 0; i < 4; ++i) {
|
|
for (int j = 0; j < 4; ++j) {
|
|
r[i * 4 + j] = a[i * 4 + 0] * b[0 * 4 + j] +
|
|
a[i * 4 + 1] * b[1 * 4 + j] +
|
|
a[i * 4 + 2] * b[2 * 4 + j] +
|
|
a[i * 4 + 3] * b[3 * 4 + j];
|
|
}
|
|
}
|
|
for (int k = 0; k < 16; ++k) out[k] = r[k];
|
|
}
|
|
|
|
inline void TransformVec4(const float* m, float x, float y, float z, float w, float* out) {
|
|
out[0] = x * m[0] + y * m[4] + z * m[8] + w * m[12];
|
|
out[1] = x * m[1] + y * m[5] + z * m[9] + w * m[13];
|
|
out[2] = x * m[2] + y * m[6] + z * m[10] + w * m[14];
|
|
out[3] = x * m[3] + y * m[7] + z * m[11] + w * m[15];
|
|
}
|
|
|
|
inline float EdgeFunction(float ax, float ay, float bx, float by, float cx, float cy) {
|
|
return (cx - ax) * (by - ay) - (cy - ay) * (bx - ax);
|
|
}
|
|
|
|
Render3DDraw ToRender3DDraw(gr2_render::Gr2MeshDraw&& mesh) {
|
|
Render3DDraw draw;
|
|
std::memcpy(draw.world, mesh.world, sizeof(draw.world));
|
|
draw.gpu_skinning=mesh.gpu_skinning;
|
|
if(mesh.geometry) {
|
|
// Source owns immutable streams; converted geometry lives with frame/resident references.
|
|
struct Entry {std::weak_ptr<const gr2_render::Gr2MeshDraw> source;std::weak_ptr<const Render3DDraw> converted;};
|
|
static std::unordered_map<const gr2_render::Gr2MeshDraw*,Entry> cache;
|
|
auto& entry=cache[mesh.geometry.get()];
|
|
if(entry.source.lock()==mesh.geometry)draw.geometry=entry.converted.lock();
|
|
if(!draw.geometry){auto source=*mesh.geometry;draw.geometry=std::make_shared<const Render3DDraw>(ToRender3DDraw(std::move(source)));entry={mesh.geometry,draw.geometry};}
|
|
if(cache.size()>1024) {
|
|
for(auto it=cache.begin();it!=cache.end();) {
|
|
if(it->second.source.expired())it=cache.erase(it);else ++it;
|
|
}
|
|
}
|
|
}
|
|
draw.texture0 = std::move(mesh.texture0);
|
|
draw.texture1 = std::move(mesh.texture1);
|
|
draw.positions = std::move(mesh.positions);
|
|
draw.normals = std::move(mesh.normals);
|
|
draw.uv0 = std::move(mesh.uv0);
|
|
draw.diffuse = std::move(mesh.diffuse);
|
|
draw.indices = std::move(mesh.indices);
|
|
draw.bone_indices = std::move(mesh.bone_indices);
|
|
draw.bone_weights = std::move(mesh.bone_weights);
|
|
draw.bone_matrices = std::move(mesh.bone_matrices);
|
|
draw.alpha_test = mesh.alpha_test;
|
|
draw.alpha_ref = mesh.alpha_ref;
|
|
draw.cull_mode = mesh.double_sided ? 1 : 2;
|
|
draw.z_write = mesh.z_write;
|
|
draw.lighting = mesh.lighting;
|
|
return draw;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
std::unique_ptr<Gr2ModelInstance> Gr2ModelInstance::Load(const std::string& filepath) {
|
|
auto impl = gr2_render::Gr2ModelInstance::Load(filepath);
|
|
if (!impl) return nullptr;
|
|
auto inst = std::make_unique<Gr2ModelInstance>();
|
|
inst->m_impl = std::shared_ptr<gr2_render::Gr2ModelInstance>(std::move(impl));
|
|
return inst;
|
|
}
|
|
|
|
std::unique_ptr<Gr2ModelInstance> Gr2ModelInstance::LoadFromMemory(const uint8_t* data, size_t size, const std::string& name) {
|
|
auto impl = gr2_render::Gr2ModelInstance::LoadFromMemory(data, size, name);
|
|
if (!impl) return nullptr;
|
|
auto inst = std::make_unique<Gr2ModelInstance>();
|
|
inst->m_impl = std::shared_ptr<gr2_render::Gr2ModelInstance>(std::move(impl));
|
|
return inst;
|
|
}
|
|
|
|
bool Gr2ModelInstance::LoadExternalAnimation(const std::string& anim_filepath) {
|
|
return m_impl ? m_impl->LoadExternalAnimation(anim_filepath) : false;
|
|
}
|
|
|
|
float Gr2ModelInstance::GetAnimationDuration() const {
|
|
return m_impl ? m_impl->GetAnimationDuration() : 0.0f;
|
|
}
|
|
|
|
void Gr2ModelInstance::SetAnimationLoop(bool underflow_loop, bool overflow_loop) {
|
|
if (m_impl) m_impl->SetAnimationLoop(underflow_loop, overflow_loop);
|
|
}
|
|
|
|
bool Gr2ModelInstance::GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time) const {
|
|
return m_impl ? m_impl->GetBoneWorldTransform(bone_name, out_matrix, animation_time) : false;
|
|
}
|
|
|
|
void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix) {
|
|
if (m_impl) {
|
|
m_impl->AttachModel(bone_name, attachment ? attachment->GetImpl() : nullptr, offset_matrix);
|
|
}
|
|
if (attachment) {
|
|
m_attached_models.push_back(attachment);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::AttachPart(std::shared_ptr<Gr2ModelInstance> part) {
|
|
if (m_impl) {
|
|
m_impl->AttachPart(part ? part->GetImpl() : nullptr);
|
|
}
|
|
if (part) {
|
|
m_attached_parts.push_back(part);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::DetachAll() {
|
|
if (m_impl) {
|
|
m_impl->DetachAll();
|
|
}
|
|
m_attached_models.clear();
|
|
m_attached_parts.clear();
|
|
}
|
|
|
|
void Gr2ModelInstance::DetachModel(const std::string& bone_name) {
|
|
if (m_impl) {
|
|
m_impl->DetachModel(bone_name);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::DetachPart(const std::shared_ptr<Gr2ModelInstance>& part) {
|
|
if (m_impl) {
|
|
m_impl->DetachPart(part ? part->GetImpl() : nullptr);
|
|
}
|
|
if (part) {
|
|
auto it = std::find(m_attached_parts.begin(), m_attached_parts.end(), part);
|
|
if (it != m_attached_parts.end()) {
|
|
m_attached_parts.erase(it);
|
|
}
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::SetAttachmentAnimated(const std::string& bone_name, bool animated) {
|
|
if (m_impl) {
|
|
m_impl->SetAttachmentAnimated(bone_name, animated);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz) {
|
|
if (m_impl) {
|
|
m_impl->SetAttachmentScale(bone_name, sx, sy, sz);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::SetSkin(const std::string& src_file_name, const std::string& dst_file_name) {
|
|
if (m_impl) {
|
|
m_impl->SetSkin(src_file_name, dst_file_name);
|
|
}
|
|
}
|
|
|
|
void Gr2ModelInstance::ClearSkins() {
|
|
if (m_impl) {
|
|
m_impl->ClearSkins();
|
|
}
|
|
}
|
|
|
|
const std::string& Gr2ModelInstance::GetFilePath() const {
|
|
static const std::string s_empty;
|
|
return m_impl ? m_impl->GetFilePath() : s_empty;
|
|
}
|
|
|
|
void Gr2ModelInstance::SetHardwareSkinningEnabled(bool enabled){hardwareSkinningEnabled=enabled;}
|
|
|
|
std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommands(float animation_time, const float* world_matrix, bool forceCPU) {
|
|
std::vector<Render3DDraw> out;
|
|
if (!m_impl) return out;
|
|
auto draws = m_impl->BuildDrawCommands(animation_time, world_matrix, hardwareSkinningEnabled && !forceCPU);
|
|
out.reserve(draws.size());
|
|
for (auto& d : draws) {
|
|
out.push_back(ToRender3DDraw(std::move(d)));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const std::vector<gr2::Mat4>& skin_matrices,
|
|
const float* world_matrix,
|
|
const gr2::Skeleton* parent_skeleton) {
|
|
std::vector<Render3DDraw> out;
|
|
if (!m_impl) return out;
|
|
auto draws = m_impl->BuildDrawCommandsWithPalette(skin_matrices, world_matrix, parent_skeleton, hardwareSkinningEnabled);
|
|
out.reserve(draws.size());
|
|
for (auto& d : draws) {
|
|
out.push_back(ToRender3DDraw(std::move(d)));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
bool Gr2ModelInstance::GetLocalBounds(float& minX, float& minY, float& minZ, float& maxX, float& maxY, float& maxZ) const {
|
|
return m_impl ? m_impl->GetLocalBounds(minX, minY, minZ, maxX, maxY, maxZ) : false;
|
|
}
|
|
|
|
Gr2SceneRenderer::Gr2SceneRenderer(int width, int height) {
|
|
for (int i = 0; i < 16; ++i) {
|
|
m_view[i] = (i % 5 == 0) ? 1.0f : 0.0f;
|
|
m_proj[i] = (i % 5 == 0) ? 1.0f : 0.0f;
|
|
}
|
|
m_logicalWidth = width;
|
|
m_logicalHeight = height;
|
|
SetViewport(0, 0, width, height);
|
|
}
|
|
|
|
Gr2SceneRenderer::~Gr2SceneRenderer() {
|
|
DestroyGPUTextures();
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetViewport(int x, int y, int width, int height) {
|
|
m_viewport[0] = x;
|
|
m_viewport[1] = y;
|
|
m_viewport[2] = width;
|
|
m_viewport[3] = height;
|
|
m_depthBuffer.assign(width * height, 1.0f);
|
|
}
|
|
|
|
const Gr2SceneRenderer::TextureData* Gr2SceneRenderer::GetTexture(const std::string& texturePath) {
|
|
if (texturePath.empty()) return nullptr;
|
|
auto it = m_textureCache.find(texturePath);
|
|
if (it != m_textureCache.end()) {
|
|
it->second.lastUsed=m_textureFrame;
|
|
return it->second.width > 0 ? &it->second : nullptr;
|
|
}
|
|
|
|
std::string clean = texturePath;
|
|
for (char& c : clean) {
|
|
if (c == '\\') c = '/';
|
|
}
|
|
if (clean.size() > 2 && clean[1] == ':') {
|
|
clean = clean.substr(2);
|
|
while (!clean.empty() && clean[0] == '/') clean = clean.substr(1);
|
|
}
|
|
|
|
std::vector<std::string> base_paths = { clean };
|
|
if (clean.size() > 4) {
|
|
std::string ext = clean.substr(clean.size() - 4);
|
|
if (ext == ".tga" || ext == ".TGA") {
|
|
std::string dds_p = clean.substr(0, clean.size() - 4) + ".dds";
|
|
base_paths.push_back(dds_p);
|
|
} else if (ext == ".dds" || ext == ".DDS") {
|
|
std::string tga_p = clean.substr(0, clean.size() - 4) + ".tga";
|
|
base_paths.push_back(tga_p);
|
|
}
|
|
}
|
|
|
|
std::vector<std::string> candidates;
|
|
for (const auto& path : base_paths) {
|
|
auto resolved = CResourceManager::GetCandidatePaths(CResourceManager::NormalizePath(path.c_str()));
|
|
candidates.insert(candidates.end(), resolved.begin(), resolved.end());
|
|
}
|
|
|
|
for (const auto& p : candidates) {
|
|
if (std::filesystem::exists(p)) {
|
|
auto img = mtimage::load_dds_path(p.c_str());
|
|
if (img.ok()) {
|
|
TextureData td;
|
|
td.width = img.w;
|
|
td.height = img.h;
|
|
td.rgba = std::move(img.rgba);td.lastUsed=m_textureFrame;
|
|
m_decodedTextureBytes+=td.rgba.size();++m_textureDecodeCount;
|
|
m_textureCache[texturePath] = std::move(td);
|
|
return &m_textureCache[texturePath];
|
|
}
|
|
}
|
|
}
|
|
|
|
TextureData emptyTd;
|
|
emptyTd.width = 0;
|
|
m_textureCache[texturePath] = std::move(emptyTd);
|
|
return nullptr;
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetCameraLookAt(float eyeX, float eyeY, float eyeZ,
|
|
float targetX, float targetY, float targetZ,
|
|
float upX, float upY, float upZ) {
|
|
m_eye[0] = eyeX;
|
|
m_eye[1] = eyeY;
|
|
m_eye[2] = eyeZ;
|
|
float fz[3] = {targetX - eyeX, targetY - eyeY, targetZ - eyeZ};
|
|
float lenZ = std::sqrt(fz[0] * fz[0] + fz[1] * fz[1] + fz[2] * fz[2]);
|
|
if (lenZ > 1e-6f) { fz[0] /= lenZ; fz[1] /= lenZ; fz[2] /= lenZ; }
|
|
|
|
float fx[3] = {
|
|
upY * fz[2] - upZ * fz[1],
|
|
upZ * fz[0] - upX * fz[2],
|
|
upX * fz[1] - upY * fz[0]
|
|
};
|
|
float lenX = std::sqrt(fx[0] * fx[0] + fx[1] * fx[1] + fx[2] * fx[2]);
|
|
if (lenX > 1e-6f) { fx[0] /= lenX; fx[1] /= lenX; fx[2] /= lenX; }
|
|
|
|
float fy[3] = {
|
|
fz[1] * fx[2] - fz[2] * fx[1],
|
|
fz[2] * fx[0] - fz[0] * fx[2],
|
|
fz[0] * fx[1] - fz[1] * fx[0]
|
|
};
|
|
|
|
// D3D row-major LookAtLH
|
|
m_view[0] = fx[0]; m_view[1] = fy[0]; m_view[2] = fz[0]; m_view[3] = 0.0f;
|
|
m_view[4] = fx[1]; m_view[5] = fy[1]; m_view[6] = fz[1]; m_view[7] = 0.0f;
|
|
m_view[8] = fx[2]; m_view[9] = fy[2]; m_view[10]= fz[2]; m_view[11]= 0.0f;
|
|
m_view[12]= -(fx[0]*eyeX + fx[1]*eyeY + fx[2]*eyeZ);
|
|
m_view[13]= -(fy[0]*eyeX + fy[1]*eyeY + fy[2]*eyeZ);
|
|
m_view[14]= -(fz[0]*eyeX + fz[1]*eyeY + fz[2]*eyeZ);
|
|
m_view[15]= 1.0f;
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetCameraLookAtRH(float eyeX, float eyeY, float eyeZ,
|
|
float targetX, float targetY, float targetZ,
|
|
float upX, float upY, float upZ) {
|
|
SetCameraLookAt(eyeX, eyeY, eyeZ, targetX, targetY, targetZ, upX, upY, upZ);
|
|
m_view[0] = -m_view[0];
|
|
m_view[4] = -m_view[4];
|
|
m_view[8] = -m_view[8];
|
|
m_view[12] = -m_view[12];
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar) {
|
|
float fovRad = fovYDegrees * 3.1415926535f / 180.0f;
|
|
float h = 1.0f / std::tan(fovRad * 0.5f);
|
|
float w = h / aspect;
|
|
float q = zFar / (zFar - zNear);
|
|
|
|
for (int i = 0; i < 16; ++i) m_proj[i] = 0.0f;
|
|
m_proj[0] = w;
|
|
m_proj[5] = h;
|
|
m_proj[10] = q;
|
|
m_proj[11] = 1.0f;
|
|
m_proj[14] = -q * zNear;
|
|
}
|
|
|
|
void Gr2SceneRenderer::Clear(uint32_t color, float depth) {
|
|
std::fill(m_depthBuffer.begin(), m_depthBuffer.end(), depth);
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetFog(bool enable, uint32_t color, float density, float fog_near, float fog_far, bool exp_mode) {
|
|
m_fog_enabled = enable;
|
|
m_fog_color = color;
|
|
m_fog_density = density;
|
|
m_fog_near = fog_near;
|
|
m_fog_far = fog_far;
|
|
m_fog_exp = exp_mode;
|
|
}
|
|
|
|
void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw& draw) {
|
|
const auto& mesh = draw.Mesh();
|
|
if (!targetSurface || mesh.indices.size() < 3 || mesh.positions.size() < 9) return;
|
|
|
|
int vpWidth = m_viewport[2];
|
|
int vpHeight = m_viewport[3];
|
|
if (vpWidth <= 0 || vpHeight <= 0) return;
|
|
|
|
// Compute composite MVP matrix (row-major: P_clip = P_world * View * Proj)
|
|
float mv[16];
|
|
MultiplyMat4(draw.world, m_view, mv);
|
|
float mvp[16];
|
|
MultiplyMat4(mv, m_proj, mvp);
|
|
|
|
std::size_t num_verts = mesh.positions.size() / 3;
|
|
struct TransformedVertex {
|
|
float x_clip = 0.0f, y_clip = 0.0f, z_clip = 0.0f, w_clip = 0.0f;
|
|
float x_screen = 0.0f, y_screen = 0.0f, z_depth = 0.0f;
|
|
float nx = 0.0f, ny = 0.0f, nz = 0.0f;
|
|
float u = 0.0f, v = 0.0f;
|
|
uint32_t diffuse = 0xFFFFFFFF;
|
|
};
|
|
std::vector<TransformedVertex> xverts(num_verts);
|
|
|
|
uint8_t mat_r = static_cast<uint8_t>(std::clamp(draw.material_diffuse[0] * 255.0f, 0.0f, 255.0f));
|
|
uint8_t mat_g = static_cast<uint8_t>(std::clamp(draw.material_diffuse[1] * 255.0f, 0.0f, 255.0f));
|
|
uint8_t mat_b = static_cast<uint8_t>(std::clamp(draw.material_diffuse[2] * 255.0f, 0.0f, 255.0f));
|
|
uint8_t mat_a = static_cast<uint8_t>(std::clamp(draw.material_diffuse[3] * 255.0f, 0.0f, 255.0f));
|
|
uint32_t default_diffuse = (mat_a << 24) | (mat_r << 16) | (mat_g << 8) | mat_b;
|
|
|
|
for (std::size_t i = 0; i < num_verts; ++i) {
|
|
float px = mesh.positions[i * 3 + 0];
|
|
float py = mesh.positions[i * 3 + 1];
|
|
float pz = mesh.positions[i * 3 + 2];
|
|
|
|
float clip[4];
|
|
TransformVec4(mvp, px, py, pz, 1.0f, clip);
|
|
xverts[i].x_clip = clip[0];
|
|
xverts[i].y_clip = clip[1];
|
|
xverts[i].z_clip = clip[2];
|
|
xverts[i].w_clip = clip[3];
|
|
|
|
if (clip[3] > 1e-5f) {
|
|
float inv_w = 1.0f / clip[3];
|
|
float ndc_x = clip[0] * inv_w;
|
|
float ndc_y = clip[1] * inv_w;
|
|
float ndc_z = clip[2] * inv_w;
|
|
|
|
xverts[i].x_screen = m_viewport[0] + (ndc_x + 1.0f) * 0.5f * vpWidth;
|
|
xverts[i].y_screen = m_viewport[1] + (1.0f - ndc_y) * 0.5f * vpHeight;
|
|
xverts[i].z_depth = ndc_z;
|
|
}
|
|
|
|
if (i * 3 + 2 < mesh.normals.size()) {
|
|
// Lit normals are transformed by the world 3x3 (D3DTS_WORLD) before N.L.
|
|
float on0 = mesh.normals[i * 3 + 0], on1 = mesh.normals[i * 3 + 1], on2 = mesh.normals[i * 3 + 2];
|
|
xverts[i].nx = on0 * draw.world[0] + on1 * draw.world[4] + on2 * draw.world[8];
|
|
xverts[i].ny = on0 * draw.world[1] + on1 * draw.world[5] + on2 * draw.world[9];
|
|
xverts[i].nz = on0 * draw.world[2] + on1 * draw.world[6] + on2 * draw.world[10];
|
|
} else {
|
|
xverts[i].nx = 0.0f; xverts[i].ny = 1.0f; xverts[i].nz = 0.0f;
|
|
}
|
|
|
|
if (i * 2 + 1 < mesh.uv0.size()) {
|
|
xverts[i].u = mesh.uv0[i * 2 + 0];
|
|
xverts[i].v = mesh.uv0[i * 2 + 1];
|
|
} else {
|
|
xverts[i].u = 0.0f; xverts[i].v = 0.0f;
|
|
}
|
|
|
|
if (i < mesh.diffuse.size()) {
|
|
xverts[i].diffuse = mesh.diffuse[i];
|
|
} else {
|
|
xverts[i].diffuse = default_diffuse;
|
|
}
|
|
}
|
|
|
|
uint32_t* dst_pixels = static_cast<uint32_t*>(targetSurface->pixels);
|
|
int dst_pitch_pixels = targetSurface->pitch / 4;
|
|
|
|
float lx = draw.light_direction[0];
|
|
float ly = draw.light_direction[1];
|
|
float lz = draw.light_direction[2];
|
|
float llen = std::sqrt(lx*lx + ly*ly + lz*lz);
|
|
if (llen > 1e-5f) { lx /= llen; ly /= llen; lz /= llen; }
|
|
|
|
float fog_r = static_cast<float>((m_fog_color >> 16) & 0xFF);
|
|
float fog_g = static_cast<float>((m_fog_color >> 8) & 0xFF);
|
|
float fog_b = static_cast<float>(m_fog_color & 0xFF);
|
|
|
|
const TextureData* diffuse_tex = nullptr;
|
|
if (!draw.texture0.empty()) {
|
|
diffuse_tex = GetTexture(draw.texture0);
|
|
}
|
|
|
|
std::size_t num_tris = mesh.indices.size() / 3;
|
|
|
|
auto make_screen_vertex = [&](TransformedVertex& v) {
|
|
if (v.w_clip > 1e-5f) {
|
|
float inv_w = 1.0f / v.w_clip;
|
|
float ndc_x = v.x_clip * inv_w;
|
|
float ndc_y = v.y_clip * inv_w;
|
|
float ndc_z = v.z_clip * inv_w;
|
|
v.x_screen = m_viewport[0] + (ndc_x + 1.0f) * 0.5f * vpWidth;
|
|
v.y_screen = m_viewport[1] + (1.0f - ndc_y) * 0.5f * vpHeight;
|
|
v.z_depth = ndc_z;
|
|
}
|
|
};
|
|
|
|
auto interpolate_vertex = [&](const TransformedVertex& a, const TransformedVertex& b, float t) -> TransformedVertex {
|
|
TransformedVertex out;
|
|
out.x_clip = a.x_clip + t * (b.x_clip - a.x_clip);
|
|
out.y_clip = a.y_clip + t * (b.y_clip - a.y_clip);
|
|
out.z_clip = a.z_clip + t * (b.z_clip - a.z_clip);
|
|
out.w_clip = a.w_clip + t * (b.w_clip - a.w_clip);
|
|
out.nx = a.nx + t * (b.nx - a.nx);
|
|
out.ny = a.ny + t * (b.ny - a.ny);
|
|
out.nz = a.nz + t * (b.nz - a.nz);
|
|
out.u = a.u + t * (b.u - a.u);
|
|
out.v = a.v + t * (b.v - a.v);
|
|
|
|
uint32_t ca = a.diffuse, cb = b.diffuse;
|
|
float r = ((ca >> 16) & 0xFF) + t * (((cb >> 16) & 0xFF) - ((ca >> 16) & 0xFF));
|
|
float g = ((ca >> 8) & 0xFF) + t * (((cb >> 8) & 0xFF) - ((ca >> 8) & 0xFF));
|
|
float bl = (ca & 0xFF) + t * ((cb & 0xFF) - (ca & 0xFF));
|
|
float al = ((ca >> 24) & 0xFF) + t * (((cb >> 24) & 0xFF) - ((ca >> 24) & 0xFF));
|
|
out.diffuse = (static_cast<uint32_t>(al) << 24) |
|
|
(static_cast<uint32_t>(r) << 16) |
|
|
(static_cast<uint32_t>(g) << 8) |
|
|
static_cast<uint32_t>(bl);
|
|
|
|
make_screen_vertex(out);
|
|
return out;
|
|
};
|
|
|
|
auto rasterize_triangle = [&](const TransformedVertex& v0, const TransformedVertex& v1, const TransformedVertex& v2) {
|
|
// Backface culling respecting draw.cull_mode (1: None, 2: CW, 3: CCW)
|
|
float area = EdgeFunction(v0.x_screen, v0.y_screen, v1.x_screen, v1.y_screen, v2.x_screen, v2.y_screen);
|
|
if (draw.cull_mode == 2 && area <= 0.0f) return;
|
|
if (draw.cull_mode == 3 && area >= 0.0f) return;
|
|
if (std::abs(area) < 1e-6f) return;
|
|
|
|
int minX = std::max(m_viewport[0], static_cast<int>(std::floor(std::min({v0.x_screen, v1.x_screen, v2.x_screen}))));
|
|
int maxX = std::min(m_viewport[0] + vpWidth - 1, static_cast<int>(std::ceil(std::max({v0.x_screen, v1.x_screen, v2.x_screen}))));
|
|
int minY = std::max(m_viewport[1], static_cast<int>(std::floor(std::min({v0.y_screen, v1.y_screen, v2.y_screen}))));
|
|
int maxY = std::min(m_viewport[1] + vpHeight - 1, static_cast<int>(std::ceil(std::max({v0.y_screen, v1.y_screen, v2.y_screen}))));
|
|
|
|
if (minX > maxX || minY > maxY) return;
|
|
|
|
float invArea = 1.0f / area;
|
|
|
|
for (int py = minY; py <= maxY; ++py) {
|
|
float fy = py + 0.5f;
|
|
|
|
float x_inter[3];
|
|
int n_inter = 0;
|
|
|
|
auto check_edge = [&](const TransformedVertex& a, const TransformedVertex& b) {
|
|
float ymin = std::min(a.y_screen, b.y_screen);
|
|
float ymax = std::max(a.y_screen, b.y_screen);
|
|
if (fy >= ymin && fy <= ymax && std::abs(b.y_screen - a.y_screen) > 1e-5f) {
|
|
float t = (fy - a.y_screen) / (b.y_screen - a.y_screen);
|
|
x_inter[n_inter++] = a.x_screen + t * (b.x_screen - a.x_screen);
|
|
}
|
|
};
|
|
check_edge(v0, v1);
|
|
check_edge(v1, v2);
|
|
check_edge(v2, v0);
|
|
|
|
if (n_inter < 2) continue;
|
|
float rx_min = x_inter[0], rx_max = x_inter[0];
|
|
for (int k = 1; k < n_inter; ++k) {
|
|
if (x_inter[k] < rx_min) rx_min = x_inter[k];
|
|
if (x_inter[k] > rx_max) rx_max = x_inter[k];
|
|
}
|
|
|
|
int rowMinX = std::max(minX, static_cast<int>(std::floor(rx_min)));
|
|
int rowMaxX = std::min(maxX, static_cast<int>(std::ceil(rx_max)));
|
|
if (rowMinX > rowMaxX) continue;
|
|
|
|
for (int px = rowMinX; px <= rowMaxX; ++px) {
|
|
float fx = px + 0.5f;
|
|
|
|
float w0 = EdgeFunction(v1.x_screen, v1.y_screen, v2.x_screen, v2.y_screen, fx, fy);
|
|
float w1 = EdgeFunction(v2.x_screen, v2.y_screen, v0.x_screen, v0.y_screen, fx, fy);
|
|
float w2 = EdgeFunction(v0.x_screen, v0.y_screen, v1.x_screen, v1.y_screen, fx, fy);
|
|
|
|
bool inside = (area > 0.0f) ? (w0 >= 0.0f && w1 >= 0.0f && w2 >= 0.0f)
|
|
: (w0 <= 0.0f && w1 <= 0.0f && w2 <= 0.0f);
|
|
|
|
if (inside) {
|
|
float b0 = w0 * invArea;
|
|
float b1 = w1 * invArea;
|
|
float b2 = w2 * invArea;
|
|
|
|
float depth = b0 * v0.z_depth + b1 * v1.z_depth + b2 * v2.z_depth;
|
|
int depth_x = px - m_viewport[0];
|
|
int depth_y = py - m_viewport[1];
|
|
if (depth_x < 0 || depth_x >= vpWidth || depth_y < 0 || depth_y >= vpHeight) continue;
|
|
int depth_idx = depth_y * vpWidth + depth_x;
|
|
if (depth >= 0.0f && depth <= 1.0f && (!draw.z_enable || depth <= m_depthBuffer[depth_idx])) {
|
|
// Smooth Phong Normal Interpolation
|
|
float nx = b0 * v0.nx + b1 * v1.nx + b2 * v2.nx;
|
|
float ny = b0 * v0.ny + b1 * v1.ny + b2 * v2.ny;
|
|
float nz = b0 * v0.nz + b1 * v1.nz + b2 * v2.nz;
|
|
float nlen = std::sqrt(nx * nx + ny * ny + nz * nz);
|
|
if (nlen > 1e-5f) { nx /= nlen; ny /= nlen; nz /= nlen; }
|
|
|
|
float ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz);
|
|
|
|
float pr = 255.0f, pg = 255.0f, pb = 255.0f;
|
|
float frag_alpha = 255.0f;
|
|
|
|
if (diffuse_tex && diffuse_tex->width > 0 && diffuse_tex->height > 0) {
|
|
float u = b0 * v0.u + b1 * v1.u + b2 * v2.u;
|
|
float v = b0 * v0.v + b1 * v1.v + b2 * v2.v;
|
|
float u_wrap = u - std::floor(u);
|
|
float v_wrap = v - std::floor(v);
|
|
int tx = std::clamp(static_cast<int>(u_wrap * diffuse_tex->width), 0, diffuse_tex->width - 1);
|
|
int ty = std::clamp(static_cast<int>(v_wrap * diffuse_tex->height), 0, diffuse_tex->height - 1);
|
|
int tex_idx = (ty * diffuse_tex->width + tx) * 4;
|
|
|
|
uint8_t ta = diffuse_tex->rgba[tex_idx + 3];
|
|
if (draw.alpha_test) {
|
|
uint32_t aref = draw.alpha_ref ? draw.alpha_ref : 70;
|
|
if (ta < aref) continue;
|
|
}
|
|
|
|
pr = diffuse_tex->rgba[tex_idx + 0];
|
|
pg = diffuse_tex->rgba[tex_idx + 1];
|
|
pb = diffuse_tex->rgba[tex_idx + 2];
|
|
frag_alpha = static_cast<float>(ta);
|
|
|
|
if (!mesh.diffuse.empty()) {
|
|
uint32_t d0 = v0.diffuse, d1 = v1.diffuse, d2 = v2.diffuse;
|
|
float vr = (b0 * ((d0 >> 16) & 0xFF) + b1 * ((d1 >> 16) & 0xFF) + b2 * ((d2 >> 16) & 0xFF)) / 255.0f;
|
|
float vg = (b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF)) / 255.0f;
|
|
float vb = (b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF)) / 255.0f;
|
|
float va = (b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF)) / 255.0f;
|
|
if (draw.lighting) {
|
|
// D3D8 fixed-function: Emissive + MatAmb*LightAmb + Diffuse*LightDiff*N.L.
|
|
float lr = std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + vr * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f);
|
|
float lg = std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + vg * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f);
|
|
float lb = std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + vb * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f);
|
|
pr = std::clamp(pr * lr, 0.0f, 255.0f);
|
|
pg = std::clamp(pg * lg, 0.0f, 255.0f);
|
|
pb = std::clamp(pb * lb, 0.0f, 255.0f);
|
|
} else {
|
|
pr = std::clamp(pr * vr, 0.0f, 255.0f);
|
|
pg = std::clamp(pg * vg, 0.0f, 255.0f);
|
|
pb = std::clamp(pb * vb, 0.0f, 255.0f);
|
|
}
|
|
frag_alpha = std::clamp(frag_alpha * va, 0.0f, 255.0f);
|
|
}
|
|
} else {
|
|
uint32_t d0 = v0.diffuse, d1 = v1.diffuse, d2 = v2.diffuse;
|
|
pr = b0 * ((d0 >> 16) & 0xFF) + b1 * ((d1 >> 16) & 0xFF) + b2 * ((d2 >> 16) & 0xFF);
|
|
pg = b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF);
|
|
pb = b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF);
|
|
frag_alpha = b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF);
|
|
if (draw.lighting) {
|
|
pr = 255.0f * std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + pr / 255.0f * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f);
|
|
pg = 255.0f * std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + pg / 255.0f * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f);
|
|
pb = 255.0f * std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + pb / 255.0f * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f);
|
|
}
|
|
}
|
|
|
|
if (m_fog_enabled && draw.fog) {
|
|
float dist = b0 * v0.w_clip + b1 * v1.w_clip + b2 * v2.w_clip;
|
|
float fog_factor = 1.0f;
|
|
if (m_fog_exp) {
|
|
fog_factor = std::exp(-std::clamp(dist * m_fog_density, 0.0f, 10.0f));
|
|
} else {
|
|
fog_factor = std::clamp((m_fog_far - dist) / (m_fog_far - m_fog_near), 0.0f, 1.0f);
|
|
}
|
|
pr = (1.0f - fog_factor) * fog_r + fog_factor * pr;
|
|
pg = (1.0f - fog_factor) * fog_g + fog_factor * pg;
|
|
pb = (1.0f - fog_factor) * fog_b + fog_factor * pb;
|
|
}
|
|
|
|
bool is_blended = draw.alpha_blend || (draw.blend_mode != 0) || (!diffuse_tex && frag_alpha < 250.0f);
|
|
if (is_blended) {
|
|
uint32_t bg = dst_pixels[py * dst_pitch_pixels + px];
|
|
float bg_r = (bg >> 16) & 0xFF;
|
|
float bg_g = (bg >> 8) & 0xFF;
|
|
float bg_b = bg & 0xFF;
|
|
float a_factor = frag_alpha / 255.0f;
|
|
|
|
if (draw.blend_mode == 1) {
|
|
pr = std::clamp(pr * a_factor + bg_r, 0.0f, 255.0f);
|
|
pg = std::clamp(pg * a_factor + bg_g, 0.0f, 255.0f);
|
|
pb = std::clamp(pb * a_factor + bg_b, 0.0f, 255.0f);
|
|
} else {
|
|
pr = pr * a_factor + bg_r * (1.0f - a_factor);
|
|
pg = pg * a_factor + bg_g * (1.0f - a_factor);
|
|
pb = pb * a_factor + bg_b * (1.0f - a_factor);
|
|
}
|
|
}
|
|
|
|
if (draw.z_write && !is_blended) {
|
|
m_depthBuffer[depth_idx] = depth;
|
|
}
|
|
|
|
uint8_t out_r = static_cast<uint8_t>(std::clamp(pr, 0.0f, 255.0f));
|
|
uint8_t out_g = static_cast<uint8_t>(std::clamp(pg, 0.0f, 255.0f));
|
|
uint8_t out_b = static_cast<uint8_t>(std::clamp(pb, 0.0f, 255.0f));
|
|
dst_pixels[py * dst_pitch_pixels + px] = (0xFFu << 24) | (out_r << 16) | (out_g << 8) | out_b;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
constexpr float W_NEAR = 0.1f;
|
|
for (std::size_t t = 0; t < num_tris; ++t) {
|
|
uint32_t i0 = mesh.indices[t * 3 + 0];
|
|
uint32_t i1 = mesh.indices[t * 3 + 1];
|
|
uint32_t i2 = mesh.indices[t * 3 + 2];
|
|
if (i0 >= num_verts || i1 >= num_verts || i2 >= num_verts) continue;
|
|
|
|
const auto& v0 = xverts[i0];
|
|
const auto& v1 = xverts[i1];
|
|
const auto& v2 = xverts[i2];
|
|
|
|
bool in0 = (v0.w_clip >= W_NEAR);
|
|
bool in1 = (v1.w_clip >= W_NEAR);
|
|
bool in2 = (v2.w_clip >= W_NEAR);
|
|
int in_count = (in0 ? 1 : 0) + (in1 ? 1 : 0) + (in2 ? 1 : 0);
|
|
|
|
if (in_count == 3) {
|
|
rasterize_triangle(v0, v1, v2);
|
|
} else if (in_count == 1) {
|
|
const TransformedVertex* vin = in0 ? &v0 : (in1 ? &v1 : &v2);
|
|
const TransformedVertex* vout1 = !in0 ? &v0 : (!in1 ? &v1 : &v2);
|
|
const TransformedVertex* vout2 = (vout1 == &v0) ? (!in1 ? &v1 : &v2) : &v2;
|
|
|
|
float denom1 = vout1->w_clip - vin->w_clip;
|
|
float denom2 = vout2->w_clip - vin->w_clip;
|
|
float t1 = std::abs(denom1) > 1e-6f ? (W_NEAR - vin->w_clip) / denom1 : 0.5f;
|
|
float t2 = std::abs(denom2) > 1e-6f ? (W_NEAR - vin->w_clip) / denom2 : 0.5f;
|
|
auto vnew1 = interpolate_vertex(*vin, *vout1, std::clamp(t1, 0.0f, 1.0f));
|
|
auto vnew2 = interpolate_vertex(*vin, *vout2, std::clamp(t2, 0.0f, 1.0f));
|
|
rasterize_triangle(*vin, vnew1, vnew2);
|
|
} else if (in_count == 2) {
|
|
const TransformedVertex* vout = !in0 ? &v0 : (!in1 ? &v1 : &v2);
|
|
const TransformedVertex* vin1 = in0 ? &v0 : (in1 ? &v1 : &v2);
|
|
const TransformedVertex* vin2 = (vin1 == &v0) ? (in1 ? &v1 : &v2) : &v2;
|
|
|
|
float denom1 = vout->w_clip - vin1->w_clip;
|
|
float denom2 = vout->w_clip - vin2->w_clip;
|
|
float t1 = std::abs(denom1) > 1e-6f ? (W_NEAR - vin1->w_clip) / denom1 : 0.5f;
|
|
float t2 = std::abs(denom2) > 1e-6f ? (W_NEAR - vin2->w_clip) / denom2 : 0.5f;
|
|
auto vnew1 = interpolate_vertex(*vin1, *vout, std::clamp(t1, 0.0f, 1.0f));
|
|
auto vnew2 = interpolate_vertex(*vin2, *vout, std::clamp(t2, 0.0f, 1.0f));
|
|
rasterize_triangle(*vin1, *vin2, vnew1);
|
|
rasterize_triangle(*vin2, vnew2, vnew1);
|
|
}
|
|
}
|
|
}
|
|
|
|
void Gr2SceneRenderer::RenderScene(SDL_Surface* targetSurface, const std::vector<Render3DDraw>& draws) {
|
|
++m_textureFrame;
|
|
for (const auto& draw : draws) {
|
|
RenderDraw(targetSurface, draw);
|
|
}
|
|
TrimTextureCaches(true);
|
|
}
|
|
|
|
void Gr2SceneRenderer::DestroyGPUTextures() {
|
|
for (auto& pair : m_gpuTextureCache) {
|
|
if (pair.second.texture) {
|
|
SDL_DestroyTexture(pair.second.texture);
|
|
}
|
|
}
|
|
m_gpuTextureCache.clear();
|
|
}
|
|
|
|
SDL_Texture* Gr2SceneRenderer::GetGPUTexture(SDL_Renderer* renderer, const std::string& texturePath) {
|
|
if (texturePath.empty() || !renderer) return nullptr;
|
|
auto it = m_gpuTextureCache.find(texturePath);
|
|
if (it != m_gpuTextureCache.end()) {it->second.lastUsed=m_textureFrame;return it->second.texture;}
|
|
|
|
const TextureData* td = GetTexture(texturePath);
|
|
if (!td || td->rgba.empty() || td->width <= 0 || td->height <= 0) {
|
|
m_gpuTextureCache[texturePath] = SDLTextureEntry{nullptr,0,m_textureFrame};
|
|
return nullptr;
|
|
}
|
|
|
|
std::vector<uint8_t> cleanRgba = td->rgba;
|
|
// Preserve RGB even where alpha is zero: opaque DDS uses alpha for specular data.
|
|
|
|
SDL_Surface* surf = SDL_CreateSurfaceFrom(td->width, td->height, SDL_PIXELFORMAT_RGBA32, (void*)cleanRgba.data(), td->width * 4);
|
|
if (!surf) {
|
|
m_gpuTextureCache[texturePath] = SDLTextureEntry{nullptr,0,m_textureFrame};
|
|
return nullptr;
|
|
}
|
|
|
|
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf);
|
|
SDL_DestroySurface(surf);
|
|
if (tex) {
|
|
SDL_SetTextureScaleMode(tex, SDL_SCALEMODE_LINEAR);
|
|
m_gpuTextureCache[texturePath] = SDLTextureEntry{tex,td->rgba.size(),m_textureFrame};
|
|
return tex;
|
|
}
|
|
m_gpuTextureCache[texturePath] = SDLTextureEntry{nullptr,0,m_textureFrame};
|
|
return nullptr;
|
|
}
|
|
|
|
void Gr2SceneRenderer::SetTextureBudgets(size_t cpuBytes,size_t gpuBytes) {
|
|
m_decodedTextureBudget=cpuBytes;m_gpuTextureBudget=gpuBytes;
|
|
if(m_hardware)m_hardware->SetTextureBudget(gpuBytes);
|
|
}
|
|
void Gr2SceneRenderer::TrimTextureCaches(bool protectDecodedWorkingSet) {
|
|
// Only evict after the scene: software draws can hold several decoded image pointers.
|
|
while(m_decodedTextureBytes>m_decodedTextureBudget || m_textureCache.size()>256) {
|
|
auto oldest=m_textureCache.end();
|
|
for(auto it=m_textureCache.begin();it!=m_textureCache.end();++it) {
|
|
if(protectDecodedWorkingSet && it->second.lastUsed>=m_textureFrame)continue;
|
|
if(oldest==m_textureCache.end() || it->second.lastUsed<oldest->second.lastUsed)oldest=it;
|
|
}
|
|
if(oldest==m_textureCache.end())break;
|
|
m_decodedTextureBytes-=oldest->second.rgba.size();m_textureCache.erase(oldest);
|
|
}
|
|
size_t bytes=0;for(const auto& [key,entry]:m_gpuTextureCache)bytes+=entry.bytes;
|
|
while(bytes>m_gpuTextureBudget || m_gpuTextureCache.size()>256) {
|
|
auto oldest=m_gpuTextureCache.end();
|
|
for(auto it=m_gpuTextureCache.begin();it!=m_gpuTextureCache.end();++it) {
|
|
if(it->second.lastUsed>=m_textureFrame)continue;
|
|
if(oldest==m_gpuTextureCache.end() || it->second.lastUsed<oldest->second.lastUsed)oldest=it;
|
|
}
|
|
if(oldest==m_gpuTextureCache.end())break;
|
|
bytes-=oldest->second.bytes;if(oldest->second.texture)SDL_DestroyTexture(oldest->second.texture);m_gpuTextureCache.erase(oldest);
|
|
}
|
|
}
|
|
void Gr2SceneRenderer::SetGPUDevice(SDL_GPUDevice* device) {
|
|
m_hardware = device ? std::make_unique<HardwareScene>(device) : nullptr;
|
|
if(m_hardware)m_hardware->SetTextureBudget(m_gpuTextureBudget);
|
|
}
|
|
|
|
void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<Render3DDraw>& draws) {
|
|
if (!renderer || draws.empty()) return;
|
|
++m_textureFrame;
|
|
|
|
int vpWidth = m_viewport[2];
|
|
int vpHeight = m_viewport[3];
|
|
if (vpWidth <= 0 || vpHeight <= 0) return;
|
|
|
|
// Metin2 Drawing Pipeline Order:
|
|
// 0: SkyDome / Skybox (no depth write)
|
|
// 1: Opaque terrain & map architecture
|
|
// 2: Characters, monsters, NPCs
|
|
// 3: Alpha-tested geometry (speedtree foliage, hair)
|
|
// 4: Translucent surfaces (water, glass) - sorted back-to-front
|
|
// 5: Additive particles, weapon shining, skill ribbons - sorted back-to-front
|
|
m_hardwareVertices.clear();
|
|
m_hardwareIndices.clear();
|
|
m_hardwareBatches.clear();
|
|
m_scratchSortedDraws.clear();
|
|
m_scratchSortedDraws.reserve(draws.size());
|
|
|
|
for (const auto& d : draws) {
|
|
DrawOrder ord;
|
|
ord.draw = &d;
|
|
const auto& sortedMesh = d.Mesh();
|
|
if (!sortedMesh.positions.empty()) {
|
|
float cx = sortedMesh.positions[0], cy = sortedMesh.positions[1], cz = sortedMesh.positions[2];
|
|
float wx = cx * d.world[0] + cy * d.world[4] + cz * d.world[8] + d.world[12];
|
|
float wy = cx * d.world[1] + cy * d.world[5] + cz * d.world[9] + d.world[13];
|
|
float wz = cx * d.world[2] + cy * d.world[6] + cz * d.world[10] + d.world[14];
|
|
float dx = wx - m_eye[0], dy = wy - m_eye[1], dz = wz - m_eye[2];
|
|
ord.depth = dx * dx + dy * dy + dz * dz;
|
|
}
|
|
|
|
if (!d.z_enable) {
|
|
ord.priority = 0; // Skybox
|
|
} else if (d.terrain) {
|
|
ord.priority = 1;
|
|
} else if (d.blend_mode == 1) {
|
|
ord.priority = 5; // Additive shining & effects
|
|
} else if (d.texture0.find("water") != std::string::npos || d.texture0.find("wave") != std::string::npos) {
|
|
ord.priority = 4; // Water
|
|
} else if (d.alpha_test) {
|
|
ord.priority = 3; // Alpha test foliage / hair
|
|
} else {
|
|
ord.priority = 1; // Opaque
|
|
}
|
|
m_scratchSortedDraws.push_back(ord);
|
|
}
|
|
|
|
std::stable_sort(m_scratchSortedDraws.begin(),m_scratchSortedDraws.end(),[this](const DrawOrder& a,const DrawOrder& b){
|
|
if(a.priority!=b.priority)return a.priority<b.priority;
|
|
if(m_hardware && a.priority==1) {
|
|
if(a.draw->alpha_blend!=b.draw->alpha_blend)return !a.draw->alpha_blend;
|
|
if(!a.draw->alpha_blend) {
|
|
if(a.draw->texture0!=b.draw->texture0)return a.draw->texture0<b.draw->texture0;
|
|
if(a.draw->geometry.get()!=b.draw->geometry.get())return std::less<const Render3DDraw*>{}(a.draw->geometry.get(),b.draw->geometry.get());
|
|
return a.depth<b.depth;
|
|
}
|
|
}
|
|
return a.depth>b.depth;
|
|
});
|
|
|
|
float fog_r = static_cast<float>((m_fog_color >> 16) & 0xFF) / 255.0f;
|
|
float fog_g = static_cast<float>((m_fog_color >> 8) & 0xFF) / 255.0f;
|
|
float fog_b = static_cast<float>(m_fog_color & 0xFF) / 255.0f;
|
|
|
|
const float NEAR_W = 0.05f;
|
|
|
|
for (const auto& ord : m_scratchSortedDraws) {
|
|
const auto& draw = *ord.draw;
|
|
const auto& mesh = draw.Mesh();
|
|
if (mesh.indices.size() < 3 || mesh.positions.size() < 9) continue;
|
|
if (draw.texture0.empty() && mesh.diffuse.empty()) continue;
|
|
|
|
float mv[16];
|
|
MultiplyMat4(draw.world, m_view, mv);
|
|
float mvp[16];
|
|
MultiplyMat4(mv, m_proj, mvp);
|
|
|
|
float lx = draw.light_direction[0];
|
|
float ly = draw.light_direction[1];
|
|
float lz = draw.light_direction[2];
|
|
float llen = std::sqrt(lx * lx + ly * ly + lz * lz);
|
|
if (llen > 1e-5f) { lx /= llen; ly /= llen; lz /= llen; }
|
|
|
|
float mat_r = std::clamp(draw.material_diffuse[0], 0.0f, 1.0f);
|
|
float mat_g = std::clamp(draw.material_diffuse[1], 0.0f, 1.0f);
|
|
float mat_b = std::clamp(draw.material_diffuse[2], 0.0f, 1.0f);
|
|
float mat_a = std::clamp(draw.material_diffuse[3], 0.0f, 1.0f);
|
|
|
|
size_t num_verts = mesh.positions.size() / 3;
|
|
if (m_hardware) {
|
|
SDL_GPUTexture* texture=nullptr;
|
|
if (!draw.texture0.empty()) {
|
|
texture=m_hardware->FindTexture(draw.texture0);
|
|
if(!texture){const auto* data=GetTexture(draw.texture0);if(!data)continue;
|
|
texture=m_hardware->Texture(draw.texture0,data->width,data->height,data->rgba.data());}
|
|
if(!texture)continue;
|
|
}
|
|
HardwareBatch batch{};batch.texture=texture;batch.cull=draw.cull_mode;
|
|
batch.depth=draw.z_enable;batch.depthWrite=draw.z_enable&&draw.z_write;
|
|
batch.blend=draw.alpha_blend;batch.additive=draw.blend_mode==1;
|
|
batch.alphaRef=draw.alpha_test ? draw.alpha_ref/255.f : -1.f;
|
|
batch.geometry=draw.geometry;
|
|
auto& t=batch.transform;std::copy_n(draw.world,16,t.world);std::copy_n(mvp,16,t.mvp);
|
|
t.diffuse[0]=mat_r;t.diffuse[1]=mat_g;t.diffuse[2]=mat_b;t.diffuse[3]=mat_a;
|
|
std::copy_n(draw.material_ambient,4,t.ambient);std::copy_n(draw.material_emissive,4,t.emissive);
|
|
t.lightDirection[0]=lx;t.lightDirection[1]=ly;t.lightDirection[2]=lz;
|
|
std::copy_n(draw.light_ambient,3,t.lightAmbient);std::copy_n(draw.light_diffuse,3,t.lightDiffuse);
|
|
t.fogColor[0]=fog_r;t.fogColor[1]=fog_g;t.fogColor[2]=fog_b;
|
|
t.fogParams[0]=m_fog_density;t.fogParams[1]=m_fog_near;t.fogParams[2]=m_fog_far;
|
|
t.modes[0]=1;t.modes[1]=draw.lighting ? 1.f : 0.f;t.modes[2]=m_fog_enabled&&draw.fog ? (m_fog_exp ? 2.f : 1.f) : 0.f;t.modes[3]=draw.z_enable ? 0.f : 1.f;
|
|
if(draw.gpu_skinning){batch.palette=draw.bone_matrices;t.skin[0]=batch.palette.size()/16;}
|
|
batch.indexCount=mesh.indices.size();
|
|
if(!batch.geometry) {
|
|
const uint32_t base=m_hardwareVertices.size();batch.firstIndex=m_hardwareIndices.size();
|
|
bool valid=true;for(auto index:mesh.indices)if(index>=num_verts){valid=false;break;}if(!valid)continue;
|
|
for(size_t i=0;i<num_verts;++i)m_hardwareVertices.push_back(MakeHardwareVertex(mesh,i));
|
|
for(auto index:mesh.indices)m_hardwareIndices.push_back(base+index);
|
|
}
|
|
m_hardwareBatches.push_back(std::move(batch));continue;
|
|
}
|
|
m_scratchGpuXverts.resize(num_verts);
|
|
auto& xverts = m_scratchGpuXverts;
|
|
|
|
for (size_t i = 0; i < num_verts; ++i) {
|
|
float px = mesh.positions[i * 3 + 0];
|
|
float py = mesh.positions[i * 3 + 1];
|
|
float pz = mesh.positions[i * 3 + 2];
|
|
|
|
float clip[4];
|
|
TransformVec4(mvp, px, py, pz, 1.0f, clip);
|
|
xverts[i].x_clip = clip[0];
|
|
xverts[i].y_clip = clip[1];
|
|
xverts[i].z_clip = clip[2];
|
|
xverts[i].w_clip = clip[3];
|
|
|
|
if (!m_hardware && clip[3] > 1e-4f) {
|
|
float inv_w = 1.0f / clip[3];
|
|
float ndc_x = clip[0] * inv_w;
|
|
float ndc_y = clip[1] * inv_w;
|
|
xverts[i].x_screen = static_cast<float>(m_viewport[0]) + (ndc_x + 1.0f) * 0.5f * static_cast<float>(vpWidth);
|
|
xverts[i].y_screen = static_cast<float>(m_viewport[1]) + (1.0f - ndc_y) * 0.5f * static_cast<float>(vpHeight);
|
|
} else {
|
|
xverts[i].x_screen = 0.0f;
|
|
xverts[i].y_screen = 0.0f;
|
|
}
|
|
|
|
if (i * 2 + 1 < mesh.uv0.size()) {
|
|
xverts[i].u = mesh.uv0[i * 2 + 0];
|
|
xverts[i].v = mesh.uv0[i * 2 + 1];
|
|
} else {
|
|
xverts[i].u = 0.0f;
|
|
xverts[i].v = 0.0f;
|
|
}
|
|
|
|
float vr = mat_r, vg = mat_g, vb = mat_b, va = mat_a;
|
|
if (i < mesh.diffuse.size()) {
|
|
uint32_t d = mesh.diffuse[i];
|
|
vr *= ((d >> 16) & 0xFF) / 255.0f;
|
|
vg *= ((d >> 8) & 0xFF) / 255.0f;
|
|
vb *= (d & 0xFF) / 255.0f;
|
|
va *= ((d >> 24) & 0xFF) / 255.0f;
|
|
}
|
|
|
|
// D3D8 fixed-function vertex lighting with one directional light (D3DRS_AMBIENT 0):
|
|
// Emissive + Material.Ambient*Light.Ambient + Diffuse*Light.Diffuse*max(0, N.L), clamped.
|
|
// Normals go through the world matrix like D3DTS_WORLD does for lit vertices.
|
|
if (draw.lighting && i * 3 + 2 < mesh.normals.size()) {
|
|
float on[3] = {mesh.normals[i * 3 + 0], mesh.normals[i * 3 + 1], mesh.normals[i * 3 + 2]};
|
|
float nx = on[0] * draw.world[0] + on[1] * draw.world[4] + on[2] * draw.world[8];
|
|
float ny = on[0] * draw.world[1] + on[1] * draw.world[5] + on[2] * draw.world[9];
|
|
float nz = on[0] * draw.world[2] + on[1] * draw.world[6] + on[2] * draw.world[10];
|
|
float nlen = std::sqrt(nx * nx + ny * ny + nz * nz);
|
|
if (nlen > 1e-5f) { nx /= nlen; ny /= nlen; nz /= nlen; }
|
|
float ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz);
|
|
vr = std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + vr * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f);
|
|
vg = std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + vg * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f);
|
|
vb = std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + vb * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f);
|
|
}
|
|
|
|
if (m_fog_enabled && draw.fog && clip[3] > 0.0f) {
|
|
float dist = clip[3];
|
|
float fog_factor = 1.0f;
|
|
if (m_fog_exp) {
|
|
fog_factor = std::exp(-std::clamp(dist * m_fog_density, 0.0f, 10.0f));
|
|
} else {
|
|
fog_factor = std::clamp((m_fog_far - dist) / (m_fog_far - m_fog_near), 0.0f, 1.0f);
|
|
}
|
|
vr = (1.0f - fog_factor) * fog_r + fog_factor * vr;
|
|
vg = (1.0f - fog_factor) * fog_g + fog_factor * vg;
|
|
vb = (1.0f - fog_factor) * fog_b + fog_factor * vb;
|
|
}
|
|
|
|
xverts[i].r = vr;
|
|
xverts[i].g = vg;
|
|
xverts[i].b = vb;
|
|
xverts[i].a = va;
|
|
}
|
|
|
|
m_scratchSdlVertices.clear();
|
|
m_scratchSdlIndices.clear();
|
|
m_scratchSdlVertices.reserve(mesh.indices.size());
|
|
m_scratchSdlIndices.reserve(mesh.indices.size());
|
|
auto& vertices = m_scratchSdlVertices;
|
|
auto& indices = m_scratchSdlIndices;
|
|
|
|
auto add_sdl_vertex = [&](const GpuTransformedVertex& gv) -> int {
|
|
SDL_Vertex sv;
|
|
sv.position.x = gv.x_screen;
|
|
sv.position.y = gv.y_screen;
|
|
sv.color.r = gv.r;
|
|
sv.color.g = gv.g;
|
|
sv.color.b = gv.b;
|
|
sv.color.a = gv.a;
|
|
sv.tex_coord.x = gv.u;
|
|
sv.tex_coord.y = gv.v;
|
|
int idx = static_cast<int>(vertices.size());
|
|
vertices.push_back(sv);
|
|
return idx;
|
|
};
|
|
|
|
auto interpolate_gpu_vertex = [&](const GpuTransformedVertex& a, const GpuTransformedVertex& b, float t) -> GpuTransformedVertex {
|
|
GpuTransformedVertex out;
|
|
out.x_clip = a.x_clip + t * (b.x_clip - a.x_clip);
|
|
out.y_clip = a.y_clip + t * (b.y_clip - a.y_clip);
|
|
out.z_clip = a.z_clip + t * (b.z_clip - a.z_clip);
|
|
out.w_clip = a.w_clip + t * (b.w_clip - a.w_clip);
|
|
out.u = a.u + t * (b.u - a.u);
|
|
out.v = a.v + t * (b.v - a.v);
|
|
out.r = a.r + t * (b.r - a.r);
|
|
out.g = a.g + t * (b.g - a.g);
|
|
out.b = a.b + t * (b.b - a.b);
|
|
out.a = a.a + t * (b.a - a.a);
|
|
if (out.w_clip > 1e-4f) {
|
|
float inv_w = 1.0f / out.w_clip;
|
|
float ndc_x = out.x_clip * inv_w;
|
|
float ndc_y = out.y_clip * inv_w;
|
|
out.x_screen = static_cast<float>(m_viewport[0]) + (ndc_x + 1.0f) * 0.5f * static_cast<float>(vpWidth);
|
|
out.y_screen = static_cast<float>(m_viewport[1]) + (1.0f - ndc_y) * 0.5f * static_cast<float>(vpHeight);
|
|
} else {
|
|
out.x_screen = 0.0f;
|
|
out.y_screen = 0.0f;
|
|
}
|
|
return out;
|
|
};
|
|
|
|
size_t num_tris = mesh.indices.size() / 3;
|
|
for (size_t t = 0; t < num_tris; ++t) {
|
|
uint32_t i0 = mesh.indices[t * 3 + 0];
|
|
uint32_t i1 = mesh.indices[t * 3 + 1];
|
|
uint32_t i2 = mesh.indices[t * 3 + 2];
|
|
if (i0 >= num_verts || i1 >= num_verts || i2 >= num_verts) continue;
|
|
|
|
const auto& v0 = xverts[i0];
|
|
const auto& v1 = xverts[i1];
|
|
const auto& v2 = xverts[i2];
|
|
|
|
int inCount = (v0.w_clip >= NEAR_W ? 1 : 0) + (v1.w_clip >= NEAR_W ? 1 : 0) + (v2.w_clip >= NEAR_W ? 1 : 0);
|
|
if (inCount == 0) continue;
|
|
|
|
auto emit_tri = [&](const GpuTransformedVertex& tv0, const GpuTransformedVertex& tv1, const GpuTransformedVertex& tv2) {
|
|
float area = EdgeFunction(tv0.x_screen, tv0.y_screen, tv1.x_screen, tv1.y_screen, tv2.x_screen, tv2.y_screen);
|
|
if (draw.cull_mode == 2 && area <= 0.0f) return;
|
|
if (draw.cull_mode == 3 && area >= 0.0f) return;
|
|
if (std::abs(area) < 1e-4f) return;
|
|
|
|
int vi0 = add_sdl_vertex(tv0);
|
|
int vi1 = add_sdl_vertex(tv1);
|
|
int vi2 = add_sdl_vertex(tv2);
|
|
indices.push_back(vi0);
|
|
indices.push_back(vi1);
|
|
indices.push_back(vi2);
|
|
};
|
|
|
|
if (inCount == 3) {
|
|
emit_tri(v0, v1, v2);
|
|
} else if (inCount == 1) {
|
|
const GpuTransformedVertex* inV = &v0;
|
|
const GpuTransformedVertex* outA = &v1;
|
|
const GpuTransformedVertex* outB = &v2;
|
|
if (v1.w_clip >= NEAR_W) { inV = &v1; outA = &v2; outB = &v0; }
|
|
else if (v2.w_clip >= NEAR_W) { inV = &v2; outA = &v0; outB = &v1; }
|
|
|
|
float tA = (NEAR_W - inV->w_clip) / (outA->w_clip - inV->w_clip);
|
|
float tB = (NEAR_W - inV->w_clip) / (outB->w_clip - inV->w_clip);
|
|
auto interA = interpolate_gpu_vertex(*inV, *outA, tA);
|
|
auto interB = interpolate_gpu_vertex(*inV, *outB, tB);
|
|
emit_tri(*inV, interA, interB);
|
|
} else if (inCount == 2) {
|
|
const GpuTransformedVertex* inA = &v0;
|
|
const GpuTransformedVertex* inB = &v1;
|
|
const GpuTransformedVertex* outV = &v2;
|
|
if (v0.w_clip < NEAR_W) { inA = &v1; inB = &v2; outV = &v0; }
|
|
else if (v1.w_clip < NEAR_W) { inA = &v2; inB = &v0; outV = &v1; }
|
|
|
|
float tA = (NEAR_W - inA->w_clip) / (outV->w_clip - inA->w_clip);
|
|
float tB = (NEAR_W - inB->w_clip) / (outV->w_clip - inB->w_clip);
|
|
auto interA = interpolate_gpu_vertex(*inA, *outV, tA);
|
|
auto interB = interpolate_gpu_vertex(*inB, *outV, tB);
|
|
emit_tri(*inA, *inB, interB);
|
|
emit_tri(*inA, interB, interA);
|
|
}
|
|
}
|
|
|
|
if (indices.empty()) continue;
|
|
|
|
SDL_Texture* gpuTex = nullptr;
|
|
if (!draw.texture0.empty()) {
|
|
gpuTex = GetGPUTexture(renderer, draw.texture0);
|
|
if (!gpuTex) {
|
|
static std::unordered_map<std::string, bool> s_missing;
|
|
if (!s_missing[draw.texture0]) {
|
|
s_missing[draw.texture0] = true;
|
|
SDL_Log("RenderSceneGPU: Texture not found (skipping white quad): %s", draw.texture0.c_str());
|
|
}
|
|
continue; // Avoid rendering raw untextured white shapes for missing textures
|
|
}
|
|
} else if (mesh.diffuse.empty()) {
|
|
// Neither texture nor vertex diffuse colors: skip blank geometry
|
|
continue;
|
|
}
|
|
|
|
if (draw.blend_mode == 1) {
|
|
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);
|
|
if (gpuTex) SDL_SetTextureBlendMode(gpuTex, SDL_BLENDMODE_ADD);
|
|
} else if (draw.alpha_blend || draw.alpha_test) {
|
|
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
|
|
if (gpuTex) SDL_SetTextureBlendMode(gpuTex, SDL_BLENDMODE_BLEND);
|
|
} else {
|
|
// Armor DDS alpha carries specular data; opaque materials do not blend it.
|
|
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
|
|
if (gpuTex) SDL_SetTextureBlendMode(gpuTex, SDL_BLENDMODE_NONE);
|
|
}
|
|
|
|
SDL_RenderGeometry(renderer, gpuTex, vertices.data(), static_cast<int>(vertices.size()), indices.data(), static_cast<int>(indices.size()));
|
|
}
|
|
if (m_hardware && !m_hardware->Render(renderer, vpWidth, vpHeight, m_hardwareVertices, m_hardwareIndices, m_hardwareBatches)) {
|
|
SDL_Log("Hardware depth pipeline unavailable, using SDL geometry fallback: %s", SDL_GetError());
|
|
m_hardware.reset();
|
|
RenderSceneGPU(renderer, draws);
|
|
}
|
|
TrimTextureCaches(m_hardware==nullptr);
|
|
}
|
|
|
|
bool Gr2SceneRenderer::ProjectToScreen(float worldX, float worldY, float worldZ, float& screenX, float& screenY) const {
|
|
float vp[16];
|
|
MultiplyMat4(m_view, m_proj, vp);
|
|
float clip[4];
|
|
TransformVec4(vp, worldX, worldY, worldZ, 1.0f, clip);
|
|
if (clip[3] <= 0.05f) return false;
|
|
float inv_w = 1.0f / clip[3];
|
|
float ndc_x = clip[0] * inv_w;
|
|
float ndc_y = clip[1] * inv_w;
|
|
if (ndc_x < -2.0f || ndc_x > 2.0f || ndc_y < -2.0f || ndc_y > 2.0f) return false;
|
|
int targetW = m_logicalWidth > 0 ? m_logicalWidth : m_viewport[2];
|
|
int targetH = m_logicalHeight > 0 ? m_logicalHeight : m_viewport[3];
|
|
screenX = static_cast<float>(m_viewport[0]) + (ndc_x + 1.0f) * 0.5f * static_cast<float>(targetW);
|
|
screenY = static_cast<float>(m_viewport[1]) + (1.0f - ndc_y) * 0.5f * static_cast<float>(targetH);
|
|
return true;
|
|
}
|
|
|
|
bool Gr2SceneRenderer::ScreenToWorldRay(float screenX, float screenY, float rayOrig[3], float rayDir[3]) const {
|
|
int targetW = m_logicalWidth > 0 ? m_logicalWidth : m_viewport[2];
|
|
int targetH = m_logicalHeight > 0 ? m_logicalHeight : m_viewport[3];
|
|
if (targetW <= 0 || targetH <= 0) return false;
|
|
if (std::abs(m_proj[0]) < 1e-6f || std::abs(m_proj[5]) < 1e-6f) return false;
|
|
|
|
// 1. Calculate NDC coordinates [-1, 1]
|
|
float ndc_x = (2.0f * (screenX - static_cast<float>(m_viewport[0]))) / static_cast<float>(targetW) - 1.0f;
|
|
float ndc_y = 1.0f - (2.0f * (screenY - static_cast<float>(m_viewport[1]))) / static_cast<float>(targetH);
|
|
|
|
// 2. View space direction from D3D perspective projection
|
|
float w = m_proj[0];
|
|
float h = m_proj[5];
|
|
float v_dir[3] = { ndc_x / w, ndc_y / h, 1.0f };
|
|
|
|
// 3. Camera eye origin in world space (upper 3x3 of D3D LookAt is orthonormal)
|
|
rayOrig[0] = -(m_view[0] * m_view[12] + m_view[1] * m_view[13] + m_view[2] * m_view[14]);
|
|
rayOrig[1] = -(m_view[4] * m_view[12] + m_view[5] * m_view[13] + m_view[6] * m_view[14]);
|
|
rayOrig[2] = -(m_view[8] * m_view[12] + m_view[9] * m_view[13] + m_view[10] * m_view[14]);
|
|
|
|
// 4. Transform view space direction to world space using R^T
|
|
float rx = v_dir[0] * m_view[0] + v_dir[1] * m_view[1] + v_dir[2] * m_view[2];
|
|
float ry = v_dir[0] * m_view[4] + v_dir[1] * m_view[5] + v_dir[2] * m_view[6];
|
|
float rz = v_dir[0] * m_view[8] + v_dir[1] * m_view[9] + v_dir[2] * m_view[10];
|
|
float len = std::sqrt(rx * rx + ry * ry + rz * rz);
|
|
if (len < 1e-6f) return false;
|
|
|
|
rayDir[0] = rx / len;
|
|
rayDir[1] = ry / len;
|
|
rayDir[2] = rz / len;
|
|
return true;
|
|
}
|
|
|
|
bool Gr2SceneRenderer::PickTerrain(float screenX, float screenY, const TerrainHeightmap& terrain,
|
|
float& pickX, float& pickY, float& pickZ, float maxRange) const {
|
|
float rayOrig[3], rayDir[3];
|
|
if (!ScreenToWorldRay(screenX, screenY, rayOrig, rayDir)) return false;
|
|
|
|
const float step = 15.0f;
|
|
float prevT = 0.0f;
|
|
float prevDiff = rayOrig[1] - terrain.GetHeightAtWorld(rayOrig[0], rayOrig[2]);
|
|
|
|
for (float t = step; t <= maxRange; t += step) {
|
|
float cx = rayOrig[0] + rayDir[0] * t;
|
|
float cz = rayOrig[2] + rayDir[2] * t;
|
|
if (cx < terrain.GetWorldMinX() || cx > terrain.GetWorldMaxX() ||
|
|
cz < terrain.GetWorldMinZ() || cz > terrain.GetWorldMaxZ()) {
|
|
continue;
|
|
}
|
|
|
|
float cy = rayOrig[1] + rayDir[1] * t;
|
|
float th = terrain.GetHeightAtWorld(cx, cz);
|
|
float diff = cy - th;
|
|
|
|
if (diff <= 0.0f && prevDiff > 0.0f) {
|
|
// Binary search refinement between prevT and t
|
|
float tLow = prevT;
|
|
float tHigh = t;
|
|
for (int iter = 0; iter < 12; ++iter) {
|
|
float tMid = (tLow + tHigh) * 0.5f;
|
|
float mx = rayOrig[0] + rayDir[0] * tMid;
|
|
float mz = rayOrig[2] + rayDir[2] * tMid;
|
|
float my = rayOrig[1] + rayDir[1] * tMid;
|
|
float mh = terrain.GetHeightAtWorld(mx, mz);
|
|
if (my <= mh) {
|
|
tHigh = tMid;
|
|
} else {
|
|
tLow = tMid;
|
|
}
|
|
}
|
|
float tFinal = (tLow + tHigh) * 0.5f;
|
|
pickX = rayOrig[0] + rayDir[0] * tFinal;
|
|
pickZ = rayOrig[2] + rayDir[2] * tFinal;
|
|
pickY = terrain.GetHeightAtWorld(pickX, pickZ);
|
|
return true;
|
|
}
|
|
prevT = t;
|
|
prevDiff = diff;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
} // namespace ava2
|