scene_renderer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #include "scene_renderer.h"
  2. #include "../game/map/terrain_service.h"
  3. #include "../game/map/visibility_service.h"
  4. #include "../game/units/spawn_type.h"
  5. #include "../game/units/troop_config.h"
  6. #include "entity/registry.h"
  7. #include "game/core/component.h"
  8. #include "game/core/world.h"
  9. #include "gl/backend.h"
  10. #include "gl/camera.h"
  11. #include "gl/primitives.h"
  12. #include "gl/resources.h"
  13. #include <QDebug>
  14. #include <algorithm>
  15. #include <cmath>
  16. namespace Render::GL {
  17. namespace {
  18. const QVector3D kAxisX(1.0f, 0.0f, 0.0f);
  19. const QVector3D kAxisY(0.0f, 1.0f, 0.0f);
  20. const QVector3D kAxisZ(0.0f, 0.0f, 1.0f);
  21. } // namespace
  22. Renderer::Renderer() { m_activeQueue = &m_queues[m_fillQueueIndex]; }
  23. Renderer::~Renderer() { shutdown(); }
  24. bool Renderer::initialize() {
  25. if (!m_backend) {
  26. m_backend = std::make_shared<Backend>();
  27. }
  28. m_backend->initialize();
  29. m_entityRegistry = std::make_unique<EntityRendererRegistry>();
  30. registerBuiltInEntityRenderers(*m_entityRegistry);
  31. return true;
  32. }
  33. void Renderer::shutdown() { m_backend.reset(); }
  34. void Renderer::beginFrame() {
  35. m_activeQueue = &m_queues[m_fillQueueIndex];
  36. m_activeQueue->clear();
  37. if (m_camera) {
  38. m_viewProj = m_camera->getProjectionMatrix() * m_camera->getViewMatrix();
  39. }
  40. if (m_backend) {
  41. m_backend->beginFrame();
  42. }
  43. }
  44. void Renderer::endFrame() {
  45. if (m_paused.load()) {
  46. return;
  47. }
  48. if (m_backend && m_camera) {
  49. std::swap(m_fillQueueIndex, m_renderQueueIndex);
  50. DrawQueue &renderQueue = m_queues[m_renderQueueIndex];
  51. renderQueue.sortForBatching();
  52. m_backend->setAnimationTime(m_accumulatedTime);
  53. m_backend->execute(renderQueue, *m_camera);
  54. }
  55. }
  56. void Renderer::setCamera(Camera *camera) { m_camera = camera; }
  57. void Renderer::setClearColor(float r, float g, float b, float a) {
  58. if (m_backend) {
  59. m_backend->setClearColor(r, g, b, a);
  60. }
  61. }
  62. void Renderer::setViewport(int width, int height) {
  63. m_viewportWidth = width;
  64. m_viewportHeight = height;
  65. if (m_backend) {
  66. m_backend->setViewport(width, height);
  67. }
  68. if (m_camera && height > 0) {
  69. float aspect = float(width) / float(height);
  70. m_camera->setPerspective(m_camera->getFOV(), aspect, m_camera->getNear(),
  71. m_camera->getFar());
  72. }
  73. }
  74. void Renderer::mesh(Mesh *mesh, const QMatrix4x4 &model, const QVector3D &color,
  75. Texture *texture, float alpha) {
  76. if (!mesh) {
  77. return;
  78. }
  79. if (mesh == getUnitCylinder() && (!texture) && (!m_currentShader)) {
  80. QVector3D start, end;
  81. float radius = 0.0f;
  82. if (detail::decomposeUnitCylinder(model, start, end, radius)) {
  83. cylinder(start, end, radius, color, alpha);
  84. return;
  85. }
  86. }
  87. MeshCmd cmd;
  88. cmd.mesh = mesh;
  89. cmd.texture = texture;
  90. cmd.model = model;
  91. cmd.mvp = m_viewProj * model;
  92. cmd.color = color;
  93. cmd.alpha = alpha;
  94. cmd.shader = m_currentShader;
  95. if (m_activeQueue) {
  96. m_activeQueue->submit(cmd);
  97. }
  98. }
  99. void Renderer::cylinder(const QVector3D &start, const QVector3D &end,
  100. float radius, const QVector3D &color, float alpha) {
  101. CylinderCmd cmd;
  102. cmd.start = start;
  103. cmd.end = end;
  104. cmd.radius = radius;
  105. cmd.color = color;
  106. cmd.alpha = alpha;
  107. if (m_activeQueue) {
  108. m_activeQueue->submit(cmd);
  109. }
  110. }
  111. void Renderer::fogBatch(const FogInstanceData *instances, std::size_t count) {
  112. if (!instances || count == 0 || !m_activeQueue) {
  113. return;
  114. }
  115. FogBatchCmd cmd;
  116. cmd.instances = instances;
  117. cmd.count = count;
  118. m_activeQueue->submit(cmd);
  119. }
  120. void Renderer::grassBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  121. const GrassBatchParams &params) {
  122. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
  123. return;
  124. }
  125. GrassBatchCmd cmd;
  126. cmd.instanceBuffer = instanceBuffer;
  127. cmd.instanceCount = instanceCount;
  128. cmd.params = params;
  129. cmd.params.time = m_accumulatedTime;
  130. m_activeQueue->submit(cmd);
  131. }
  132. void Renderer::stoneBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  133. const StoneBatchParams &params) {
  134. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
  135. return;
  136. }
  137. StoneBatchCmd cmd;
  138. cmd.instanceBuffer = instanceBuffer;
  139. cmd.instanceCount = instanceCount;
  140. cmd.params = params;
  141. m_activeQueue->submit(cmd);
  142. }
  143. void Renderer::plantBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  144. const PlantBatchParams &params) {
  145. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
  146. return;
  147. }
  148. PlantBatchCmd cmd;
  149. cmd.instanceBuffer = instanceBuffer;
  150. cmd.instanceCount = instanceCount;
  151. cmd.params = params;
  152. cmd.params.time = m_accumulatedTime;
  153. m_activeQueue->submit(cmd);
  154. }
  155. void Renderer::pineBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  156. const PineBatchParams &params) {
  157. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
  158. return;
  159. }
  160. PineBatchCmd cmd;
  161. cmd.instanceBuffer = instanceBuffer;
  162. cmd.instanceCount = instanceCount;
  163. cmd.params = params;
  164. cmd.params.time = m_accumulatedTime;
  165. m_activeQueue->submit(cmd);
  166. }
  167. void Renderer::firecampBatch(Buffer *instanceBuffer, std::size_t instanceCount,
  168. const FireCampBatchParams &params) {
  169. if (!instanceBuffer || instanceCount == 0 || !m_activeQueue) {
  170. return;
  171. }
  172. FireCampBatchCmd cmd;
  173. cmd.instanceBuffer = instanceBuffer;
  174. cmd.instanceCount = instanceCount;
  175. cmd.params = params;
  176. cmd.params.time = m_accumulatedTime;
  177. m_activeQueue->submit(cmd);
  178. }
  179. void Renderer::terrainChunk(Mesh *mesh, const QMatrix4x4 &model,
  180. const TerrainChunkParams &params,
  181. std::uint16_t sortKey, bool depthWrite,
  182. float depthBias) {
  183. if (!mesh || !m_activeQueue) {
  184. return;
  185. }
  186. TerrainChunkCmd cmd;
  187. cmd.mesh = mesh;
  188. cmd.model = model;
  189. cmd.params = params;
  190. cmd.sortKey = sortKey;
  191. cmd.depthWrite = depthWrite;
  192. cmd.depthBias = depthBias;
  193. m_activeQueue->submit(cmd);
  194. }
  195. void Renderer::selectionRing(const QMatrix4x4 &model, float alphaInner,
  196. float alphaOuter, const QVector3D &color) {
  197. SelectionRingCmd cmd;
  198. cmd.model = model;
  199. cmd.mvp = m_viewProj * model;
  200. cmd.alphaInner = alphaInner;
  201. cmd.alphaOuter = alphaOuter;
  202. cmd.color = color;
  203. if (m_activeQueue) {
  204. m_activeQueue->submit(cmd);
  205. }
  206. }
  207. void Renderer::grid(const QMatrix4x4 &model, const QVector3D &color,
  208. float cellSize, float thickness, float extent) {
  209. GridCmd cmd;
  210. cmd.model = model;
  211. cmd.mvp = m_viewProj * model;
  212. cmd.color = color;
  213. cmd.cellSize = cellSize;
  214. cmd.thickness = thickness;
  215. cmd.extent = extent;
  216. if (m_activeQueue) {
  217. m_activeQueue->submit(cmd);
  218. }
  219. }
  220. void Renderer::selectionSmoke(const QMatrix4x4 &model, const QVector3D &color,
  221. float baseAlpha) {
  222. SelectionSmokeCmd cmd;
  223. cmd.model = model;
  224. cmd.mvp = m_viewProj * model;
  225. cmd.color = color;
  226. cmd.baseAlpha = baseAlpha;
  227. if (m_activeQueue) {
  228. m_activeQueue->submit(cmd);
  229. }
  230. }
  231. void Renderer::enqueueSelectionRing(Engine::Core::Entity *,
  232. Engine::Core::TransformComponent *transform,
  233. Engine::Core::UnitComponent *unitComp,
  234. bool selected, bool hovered) {
  235. if ((!selected && !hovered) || !transform) {
  236. return;
  237. }
  238. float ringSize = 0.5f;
  239. float ringOffset = 0.05f;
  240. float groundOffset = 0.0f;
  241. if (unitComp) {
  242. auto &config = Game::Units::TroopConfig::instance();
  243. ringSize = config.getSelectionRingSize(unitComp->spawnType);
  244. ringOffset += config.getSelectionRingYOffset(unitComp->spawnType);
  245. groundOffset = config.getSelectionRingGroundOffset(unitComp->spawnType);
  246. }
  247. QVector3D pos(transform->position.x, transform->position.y,
  248. transform->position.z);
  249. auto &terrainService = Game::Map::TerrainService::instance();
  250. float terrainY = transform->position.y;
  251. if (terrainService.isInitialized()) {
  252. terrainY = terrainService.getTerrainHeight(pos.x(), pos.z());
  253. } else {
  254. terrainY -= groundOffset * transform->scale.y;
  255. }
  256. pos.setY(terrainY);
  257. QMatrix4x4 ringModel;
  258. ringModel.translate(pos.x(), pos.y() + ringOffset, pos.z());
  259. ringModel.scale(ringSize, 1.0f, ringSize);
  260. if (selected) {
  261. selectionRing(ringModel, 0.6f, 0.25f, QVector3D(0.2f, 0.4f, 1.0f));
  262. } else if (hovered) {
  263. selectionRing(ringModel, 0.35f, 0.15f, QVector3D(0.90f, 0.90f, 0.25f));
  264. }
  265. }
  266. void Renderer::renderWorld(Engine::Core::World *world) {
  267. if (m_paused.load()) {
  268. return;
  269. }
  270. if (!world) {
  271. return;
  272. }
  273. std::lock_guard<std::recursive_mutex> guard(world->getEntityMutex());
  274. auto &vis = Game::Map::VisibilityService::instance();
  275. const bool visibilityEnabled = vis.isInitialized();
  276. auto renderableEntities =
  277. world->getEntitiesWith<Engine::Core::RenderableComponent>();
  278. for (auto entity : renderableEntities) {
  279. if (entity->hasComponent<Engine::Core::PendingRemovalComponent>()) {
  280. continue;
  281. }
  282. auto renderable = entity->getComponent<Engine::Core::RenderableComponent>();
  283. auto transform = entity->getComponent<Engine::Core::TransformComponent>();
  284. if (!renderable->visible || !transform) {
  285. continue;
  286. }
  287. auto *unitComp = entity->getComponent<Engine::Core::UnitComponent>();
  288. if (unitComp && unitComp->health <= 0) {
  289. continue;
  290. }
  291. if (m_camera && unitComp) {
  292. float cullRadius = 3.0f;
  293. if (unitComp->spawnType == Game::Units::SpawnType::MountedKnight) {
  294. cullRadius = 4.0f;
  295. } else if (unitComp->spawnType == Game::Units::SpawnType::Spearman ||
  296. unitComp->spawnType == Game::Units::SpawnType::Archer ||
  297. unitComp->spawnType == Game::Units::SpawnType::Knight) {
  298. cullRadius = 2.5f;
  299. }
  300. QVector3D unitPos(transform->position.x, transform->position.y,
  301. transform->position.z);
  302. if (!m_camera->isInFrustum(unitPos, cullRadius)) {
  303. continue;
  304. }
  305. }
  306. if (unitComp && unitComp->ownerId != m_localOwnerId) {
  307. if (visibilityEnabled) {
  308. if (!vis.isVisibleWorld(transform->position.x, transform->position.z)) {
  309. continue;
  310. }
  311. }
  312. }
  313. bool isSelected =
  314. (m_selectedIds.find(entity->getId()) != m_selectedIds.end());
  315. bool isHovered = (entity->getId() == m_hoveredEntityId);
  316. QMatrix4x4 modelMatrix;
  317. modelMatrix.translate(transform->position.x, transform->position.y,
  318. transform->position.z);
  319. modelMatrix.rotate(transform->rotation.x, kAxisX);
  320. modelMatrix.rotate(transform->rotation.y, kAxisY);
  321. modelMatrix.rotate(transform->rotation.z, kAxisZ);
  322. modelMatrix.scale(transform->scale.x, transform->scale.y,
  323. transform->scale.z);
  324. bool drawnByRegistry = false;
  325. if (unitComp && m_entityRegistry) {
  326. std::string unitTypeStr =
  327. Game::Units::spawnTypeToString(unitComp->spawnType);
  328. auto fn = m_entityRegistry->get(unitTypeStr);
  329. if (fn) {
  330. DrawContext ctx{resources(), entity, world, modelMatrix};
  331. ctx.selected = isSelected;
  332. ctx.hovered = isHovered;
  333. ctx.animationTime = m_accumulatedTime;
  334. ctx.backend = m_backend.get();
  335. fn(ctx, *this);
  336. enqueueSelectionRing(entity, transform, unitComp, isSelected,
  337. isHovered);
  338. drawnByRegistry = true;
  339. }
  340. }
  341. if (drawnByRegistry) {
  342. continue;
  343. }
  344. Mesh *meshToDraw = nullptr;
  345. ResourceManager *res = resources();
  346. switch (renderable->mesh) {
  347. case Engine::Core::RenderableComponent::MeshKind::Quad:
  348. meshToDraw = res ? res->quad() : nullptr;
  349. break;
  350. case Engine::Core::RenderableComponent::MeshKind::Plane:
  351. meshToDraw = res ? res->ground() : nullptr;
  352. break;
  353. case Engine::Core::RenderableComponent::MeshKind::Cube:
  354. meshToDraw = res ? res->unit() : nullptr;
  355. break;
  356. case Engine::Core::RenderableComponent::MeshKind::Capsule:
  357. meshToDraw = nullptr;
  358. break;
  359. case Engine::Core::RenderableComponent::MeshKind::Ring:
  360. meshToDraw = nullptr;
  361. break;
  362. case Engine::Core::RenderableComponent::MeshKind::None:
  363. default:
  364. break;
  365. }
  366. if (!meshToDraw && res) {
  367. meshToDraw = res->unit();
  368. }
  369. if (!meshToDraw && res) {
  370. meshToDraw = res->quad();
  371. }
  372. QVector3D color = QVector3D(renderable->color[0], renderable->color[1],
  373. renderable->color[2]);
  374. if (res) {
  375. Mesh *contactQuad = res->quad();
  376. Texture *white = res->white();
  377. if (contactQuad && white) {
  378. QMatrix4x4 contactBase;
  379. contactBase.translate(transform->position.x,
  380. transform->position.y + 0.03f,
  381. transform->position.z);
  382. contactBase.rotate(-90.0f, 1.0f, 0.0f, 0.0f);
  383. float footprint =
  384. std::max({transform->scale.x, transform->scale.z, 0.6f});
  385. float sizeRatio = 1.0f;
  386. if (auto *unit = entity->getComponent<Engine::Core::UnitComponent>()) {
  387. int mh = std::max(1, unit->maxHealth);
  388. sizeRatio = std::clamp(unit->health / float(mh), 0.0f, 1.0f);
  389. }
  390. float eased = 0.25f + 0.75f * sizeRatio;
  391. float baseScaleX = footprint * 0.55f * eased;
  392. float baseScaleY = footprint * 0.35f * eased;
  393. QVector3D col(0.03f, 0.03f, 0.03f);
  394. float centerAlpha = 0.32f * eased;
  395. float midAlpha = 0.16f * eased;
  396. float outerAlpha = 0.07f * eased;
  397. QMatrix4x4 c0 = contactBase;
  398. c0.scale(baseScaleX * 0.60f, baseScaleY * 0.60f, 1.0f);
  399. mesh(contactQuad, c0, col, white, centerAlpha);
  400. QMatrix4x4 c1 = contactBase;
  401. c1.scale(baseScaleX * 0.95f, baseScaleY * 0.95f, 1.0f);
  402. mesh(contactQuad, c1, col, white, midAlpha);
  403. QMatrix4x4 c2 = contactBase;
  404. c2.scale(baseScaleX * 1.35f, baseScaleY * 1.35f, 1.0f);
  405. mesh(contactQuad, c2, col, white, outerAlpha);
  406. }
  407. }
  408. enqueueSelectionRing(entity, transform, unitComp, isSelected, isHovered);
  409. mesh(meshToDraw, modelMatrix, color, res ? res->white() : nullptr, 1.0f);
  410. }
  411. }
  412. } // namespace Render::GL