campaign_map_view.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735
  1. #include "campaign_map_view.h"
  2. #include "campaign_map_render_utils.h"
  3. #include "../utils/resource_utils.h"
  4. #include <QDateTime>
  5. #include <QDebug>
  6. #include <QFile>
  7. #include <QImage>
  8. #include <QJsonArray>
  9. #include <QJsonDocument>
  10. #include <QJsonObject>
  11. #include <QMatrix4x4>
  12. #include <QOpenGLContext>
  13. #include <QOpenGLFramebufferObject>
  14. #include <QOpenGLFramebufferObjectFormat>
  15. #include <QOpenGLFunctions_3_3_Core>
  16. #include <QOpenGLShaderProgram>
  17. #include <QOpenGLTexture>
  18. #include <QVariantMap>
  19. #include <QVector2D>
  20. #include <QVector3D>
  21. #include <QVector4D>
  22. #include <QtGlobal>
  23. #include <QtMath>
  24. #include <cmath>
  25. #include <cstring>
  26. #include <unordered_map>
  27. #include <utility>
  28. #include <vector>
  29. namespace {
  30. auto build_mvp_matrix(float width, float height, float yaw_deg, float pitch_deg,
  31. float distance, float pan_u, float pan_v) -> QMatrix4x4 {
  32. const float view_w = qMax(1.0F, width);
  33. const float view_h = qMax(1.0F, height);
  34. const float aspect = view_w / view_h;
  35. QMatrix4x4 projection;
  36. projection.perspective(45.0F, aspect, 0.1F, 10.0F);
  37. const float clamped_pan_u = qBound(-0.5F, pan_u, 0.5F);
  38. const float clamped_pan_v = qBound(-0.5F, pan_v, 0.5F);
  39. const QVector3D center(0.5F + clamped_pan_u, 0.0F, 0.5F + clamped_pan_v);
  40. const float yaw_rad = qDegreesToRadians(yaw_deg);
  41. const float pitch_rad = qDegreesToRadians(pitch_deg);
  42. const float clamped_distance =
  43. qMax(CampaignMapView::k_min_orbit_distance, distance);
  44. const float cos_pitch = std::cos(pitch_rad);
  45. const float sin_pitch = std::sin(pitch_rad);
  46. const float cos_yaw = std::cos(yaw_rad);
  47. const float sin_yaw = std::sin(yaw_rad);
  48. QVector3D eye(center.x() + clamped_distance * sin_yaw * cos_pitch,
  49. center.y() + clamped_distance * sin_pitch,
  50. center.z() + clamped_distance * cos_yaw * cos_pitch);
  51. QMatrix4x4 view;
  52. view.lookAt(eye, center, QVector3D(0.0F, 0.0F, 1.0F));
  53. QMatrix4x4 model;
  54. return projection * view * model;
  55. }
  56. auto point_in_triangle(const QVector2D &p, const QVector2D &a,
  57. const QVector2D &b, const QVector2D &c) -> bool {
  58. const QVector2D v0 = c - a;
  59. const QVector2D v1 = b - a;
  60. const QVector2D v2 = p - a;
  61. const float dot00 = QVector2D::dotProduct(v0, v0);
  62. const float dot01 = QVector2D::dotProduct(v0, v1);
  63. const float dot02 = QVector2D::dotProduct(v0, v2);
  64. const float dot11 = QVector2D::dotProduct(v1, v1);
  65. const float dot12 = QVector2D::dotProduct(v1, v2);
  66. const float denom = dot00 * dot11 - dot01 * dot01;
  67. if (qFuzzyIsNull(denom)) {
  68. return false;
  69. }
  70. const float inv_denom = 1.0F / denom;
  71. const float u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
  72. const float v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
  73. return (u >= 0.0F) && (v >= 0.0F) && (u + v <= 1.0F);
  74. }
  75. struct LineSpan {
  76. int start = 0;
  77. int count = 0;
  78. };
  79. struct LineLayer {
  80. GLuint vao = 0;
  81. GLuint vbo = 0;
  82. std::vector<LineSpan> spans;
  83. QVector4D color = QVector4D(1.0F, 1.0F, 1.0F, 1.0F);
  84. float width = 1.0F;
  85. bool ready = false;
  86. bool double_stroke = false;
  87. QVector4D outer_color = QVector4D(0.12F, 0.10F, 0.08F, 0.95F);
  88. QVector4D inner_color = QVector4D(0.55F, 0.50F, 0.42F, 0.75F);
  89. float outer_width_ratio = 1.8F;
  90. float inner_width_ratio = 1.0F;
  91. };
  92. struct StrokeMesh {
  93. GLuint vao = 0;
  94. GLuint vbo = 0;
  95. int vertex_count = 0;
  96. float width = 0.0F;
  97. bool ready = false;
  98. };
  99. struct PathLine {
  100. std::vector<QVector2D> points;
  101. StrokeMesh border;
  102. StrokeMesh highlight;
  103. StrokeMesh core;
  104. };
  105. struct PathLayer {
  106. std::vector<PathLine> lines;
  107. bool ready = false;
  108. };
  109. struct ProvinceSpan {
  110. int start = 0;
  111. int count = 0;
  112. QVector4D color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  113. QVector4D base_color = QVector4D(0.0F, 0.0F, 0.0F, 0.0F);
  114. QString id;
  115. };
  116. struct ProvinceLayer {
  117. GLuint vao = 0;
  118. GLuint vbo = 0;
  119. std::vector<ProvinceSpan> spans;
  120. bool ready = false;
  121. };
  122. struct MissionBadge {
  123. GLuint vao = 0;
  124. GLuint vbo = 0;
  125. int vertex_count = 0;
  126. QVector2D position;
  127. bool ready = false;
  128. int style = 3;
  129. QVector4D primary_color = QVector4D(0.75F, 0.18F, 0.12F, 1.0F);
  130. QVector4D secondary_color = QVector4D(0.95F, 0.85F, 0.45F, 1.0F);
  131. QVector4D border_color = QVector4D(0.15F, 0.10F, 0.08F, 1.0F);
  132. QVector4D shadow_color = QVector4D(0.0F, 0.0F, 0.0F, 0.4F);
  133. float size = 0.025F;
  134. float border_width = 2.0F;
  135. bool show_shadow = true;
  136. };
  137. struct CartographicSymbolInstance {
  138. QVector2D position;
  139. int symbol_type;
  140. float size;
  141. int importance;
  142. };
  143. struct CartographicSymbolLayer {
  144. GLuint vao = 0;
  145. GLuint vbo = 0;
  146. std::vector<CartographicSymbolInstance> symbols;
  147. std::vector<LineSpan> spans;
  148. int total_vertices = 0;
  149. bool ready = false;
  150. QVector4D fill_color = QVector4D(0.35F, 0.30F, 0.25F, 0.85F);
  151. QVector4D stroke_color = QVector4D(0.18F, 0.15F, 0.12F, 0.95F);
  152. QVector4D shadow_color = QVector4D(0.0F, 0.0F, 0.0F, 0.35F);
  153. float stroke_width = 1.5F;
  154. bool show_shadow = true;
  155. };
  156. struct TerrainMesh {
  157. GLuint vao = 0;
  158. GLuint vbo = 0;
  159. int vertex_count = 0;
  160. bool ready = false;
  161. float height_scale = 0.05F;
  162. float z_base = 0.0F;
  163. };
  164. struct HillshadeLayer {
  165. GLuint texture_id = 0;
  166. int width = 0;
  167. int height = 0;
  168. bool ready = false;
  169. QVector3D light_direction{0.35F, 0.85F, 0.40F};
  170. float ambient = 0.25F;
  171. float intensity = 1.0F;
  172. };
  173. struct HeightmapData {
  174. std::vector<float> samples;
  175. int width = 0;
  176. int height = 0;
  177. float min_m = 0.0F;
  178. float max_m = 0.0F;
  179. bool ready = false;
  180. };
  181. struct ProvinceLabel {
  182. QString text;
  183. QVector2D position;
  184. int importance;
  185. bool is_sea = false;
  186. };
  187. struct LabelLayer {
  188. GLuint vao = 0;
  189. GLuint vbo = 0;
  190. std::vector<ProvinceLabel> labels;
  191. int total_vertices = 0;
  192. bool ready = false;
  193. GLuint font_texture = 0;
  194. };
  195. struct QStringHash {
  196. std::size_t operator()(const QString &s) const noexcept { return qHash(s); }
  197. };
  198. struct CampaignMapTextureCache {
  199. static CampaignMapTextureCache &instance() {
  200. static CampaignMapTextureCache s_instance;
  201. return s_instance;
  202. }
  203. QOpenGLTexture *get_or_load(const QString &resource_path) {
  204. if (!m_allow_loading) {
  205. qWarning() << "CampaignMapTextureCache: Attempted to load texture after "
  206. "initialization:"
  207. << resource_path;
  208. return nullptr;
  209. }
  210. auto it = m_textures.find(resource_path);
  211. if (it != m_textures.end() && it->second != nullptr) {
  212. return it->second;
  213. }
  214. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  215. QImage image(path);
  216. if (image.isNull()) {
  217. qWarning() << "CampaignMapTextureCache: Failed to load texture" << path;
  218. return nullptr;
  219. }
  220. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  221. auto *texture = new QOpenGLTexture(rgba);
  222. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  223. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  224. m_textures[resource_path] = texture;
  225. return texture;
  226. }
  227. void set_loading_allowed(bool allowed) { m_allow_loading = allowed; }
  228. void clear() {
  229. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  230. if (ctx != nullptr && ctx->isValid()) {
  231. for (auto &pair : m_textures) {
  232. delete pair.second;
  233. }
  234. }
  235. m_textures.clear();
  236. }
  237. private:
  238. CampaignMapTextureCache() = default;
  239. ~CampaignMapTextureCache() { clear(); }
  240. std::unordered_map<QString, QOpenGLTexture *, QStringHash> m_textures;
  241. bool m_allow_loading = true;
  242. };
  243. class CampaignMapRenderer : public QQuickFramebufferObject::Renderer,
  244. protected QOpenGLFunctions_3_3_Core {
  245. public:
  246. CampaignMapRenderer() = default;
  247. ~CampaignMapRenderer() override { cleanup(); }
  248. void render() override {
  249. if (!ensure_initialized()) {
  250. return;
  251. }
  252. glViewport(0, 0, m_size.width(), m_size.height());
  253. glEnable(GL_DEPTH_TEST);
  254. glDisable(GL_CULL_FACE);
  255. glEnable(GL_BLEND);
  256. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  257. glClearColor(0.157F, 0.267F, 0.361F, 1.0F);
  258. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  259. QMatrix4x4 mvp;
  260. compute_mvp(mvp);
  261. draw_textured_layer(m_water_texture, m_quad_vao, 6, mvp, 1.0F, -0.01F);
  262. if (m_terrain_mesh.ready && m_terrain_program.isLinked()) {
  263. draw_terrain_layer(m_terrain_mesh, mvp);
  264. } else if (m_land_vertex_count > 0) {
  265. draw_textured_layer(m_base_texture, m_land_vao, m_land_vertex_count, mvp,
  266. 1.0F, 0.0F);
  267. } else {
  268. draw_textured_layer(m_base_texture, m_quad_vao, 6, mvp, 1.0F, 0.0F);
  269. }
  270. glDisable(GL_DEPTH_TEST);
  271. if (m_show_province_fills) {
  272. draw_province_layer(m_province_layer, mvp, 0.002F);
  273. }
  274. draw_line_layer(m_province_border_layer, mvp, 0.0045F);
  275. draw_line_layer(m_coast_layer, mvp, 0.004F);
  276. draw_line_layer(m_river_layer, mvp, 0.003F);
  277. draw_progressive_path_layers(m_path_layer, mvp, 0.006F);
  278. draw_symbol_layer(m_symbol_layer, mvp, 0.007F);
  279. draw_mission_badge(m_mission_badge, mvp, 0.008F);
  280. draw_label_layer(m_label_layer, mvp, 0.009F);
  281. if (!m_hover_province_id.isEmpty()) {
  282. qint64 now = QDateTime::currentMSecsSinceEpoch();
  283. if (now - m_last_update_time >= 16) {
  284. m_last_update_time = now;
  285. update();
  286. }
  287. }
  288. }
  289. auto createFramebufferObject(const QSize &size)
  290. -> QOpenGLFramebufferObject * override {
  291. m_size = size;
  292. QOpenGLFramebufferObjectFormat fmt;
  293. fmt.setAttachment(QOpenGLFramebufferObject::Depth);
  294. fmt.setSamples(0);
  295. return new QOpenGLFramebufferObject(size, fmt);
  296. }
  297. void synchronize(QQuickFramebufferObject *item) override {
  298. auto *view = dynamic_cast<CampaignMapView *>(item);
  299. if (view == nullptr) {
  300. return;
  301. }
  302. m_orbit_yaw = view->orbit_yaw();
  303. m_orbit_pitch = view->orbit_pitch();
  304. m_orbit_distance = view->orbit_distance();
  305. m_pan_u = view->pan_u();
  306. m_pan_v = view->pan_v();
  307. m_terrain_height_scale = view->terrain_height_scale();
  308. m_show_province_fills = view->show_province_fills();
  309. QString new_hover_id = view->hover_province_id();
  310. if (m_hover_province_id != new_hover_id) {
  311. m_hover_start_time = QDateTime::currentMSecsSinceEpoch();
  312. m_hover_province_id = new_hover_id;
  313. }
  314. m_current_mission = view->current_mission();
  315. if (m_province_state_version != view->province_state_version() &&
  316. m_province_layer.ready) {
  317. apply_province_overrides(view->province_overrides());
  318. m_province_state_version = view->province_state_version();
  319. }
  320. }
  321. private:
  322. QSize m_size;
  323. bool m_initialized = false;
  324. QOpenGLShaderProgram m_texture_program;
  325. QOpenGLShaderProgram m_line_program;
  326. QOpenGLShaderProgram m_terrain_program;
  327. QOpenGLShaderProgram m_label_program;
  328. GLuint m_quad_vao = 0;
  329. GLuint m_quad_vbo = 0;
  330. GLuint m_land_vao = 0;
  331. GLuint m_land_vbo = 0;
  332. int m_land_vertex_count = 0;
  333. QOpenGLTexture *m_base_texture = nullptr;
  334. QOpenGLTexture *m_water_texture = nullptr;
  335. LineLayer m_coast_layer;
  336. LineLayer m_river_layer;
  337. PathLayer m_path_layer;
  338. LineLayer m_province_border_layer;
  339. ProvinceLayer m_province_layer;
  340. MissionBadge m_mission_badge;
  341. CartographicSymbolLayer m_symbol_layer;
  342. TerrainMesh m_terrain_mesh;
  343. HillshadeLayer m_hillshade;
  344. LabelLayer m_label_layer;
  345. float m_orbit_yaw = 185.0F;
  346. float m_orbit_pitch = 52.0F;
  347. float m_orbit_distance = 1.35F;
  348. float m_pan_u = 0.0F;
  349. float m_pan_v = 0.0F;
  350. QString m_hover_province_id;
  351. int m_province_state_version = 0;
  352. int m_current_mission = 7;
  353. float m_terrain_height_scale = 1.0F;
  354. bool m_show_province_fills = true;
  355. qint64 m_hover_start_time = 0;
  356. qint64 m_last_update_time = 0;
  357. auto ensure_initialized() -> bool {
  358. if (m_initialized) {
  359. return true;
  360. }
  361. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  362. if (ctx == nullptr || !ctx->isValid()) {
  363. qWarning() << "CampaignMapRenderer: No valid OpenGL context";
  364. return false;
  365. }
  366. initializeOpenGLFunctions();
  367. if (!init_shaders()) {
  368. return false;
  369. }
  370. init_quad();
  371. auto &tex_cache = CampaignMapTextureCache::instance();
  372. tex_cache.set_loading_allowed(true);
  373. m_water_texture = tex_cache.get_or_load(
  374. QStringLiteral(":/assets/campaign_map/campaign_water.png"));
  375. m_base_texture = tex_cache.get_or_load(
  376. QStringLiteral(":/assets/campaign_map/campaign_base_color.png"));
  377. tex_cache.set_loading_allowed(false);
  378. init_land_mesh();
  379. init_line_layer(m_coast_layer,
  380. QStringLiteral(":/assets/campaign_map/coastlines_uv.json"),
  381. QVector4D(0.12F, 0.10F, 0.08F, 0.95F), 2.5F);
  382. m_coast_layer.double_stroke = true;
  383. m_coast_layer.outer_color = QVector4D(0.12F, 0.10F, 0.08F, 0.95F);
  384. m_coast_layer.inner_color = QVector4D(0.55F, 0.50F, 0.42F, 0.75F);
  385. init_line_layer(m_river_layer,
  386. QStringLiteral(":/assets/campaign_map/rivers_uv.json"),
  387. QVector4D(0.35F, 0.48F, 0.58F, 0.90F), 1.5F);
  388. init_path_layer(m_path_layer,
  389. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  390. init_province_layer(m_province_layer,
  391. QStringLiteral(":/assets/campaign_map/provinces.json"));
  392. init_borders_layer(m_province_border_layer,
  393. QStringLiteral(":/assets/campaign_map/provinces.json"),
  394. QVector4D(0.25F, 0.22F, 0.20F, 0.65F), 1.2F);
  395. init_symbol_layer(m_symbol_layer,
  396. QStringLiteral(":/assets/campaign_map/provinces.json"));
  397. init_terrain_mesh(m_terrain_mesh, 128);
  398. init_hillshade_layer(m_hillshade, 256, 256);
  399. init_label_layer(m_label_layer,
  400. QStringLiteral(":/assets/campaign_map/provinces.json"));
  401. m_initialized = true;
  402. return true;
  403. }
  404. auto init_shaders() -> bool {
  405. static const char *kTexVert = R"(
  406. #version 330 core
  407. layout(location = 0) in vec2 a_pos;
  408. uniform mat4 u_mvp;
  409. uniform float u_z;
  410. out vec2 v_uv;
  411. void main() {
  412. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  413. gl_Position = u_mvp * vec4(world, 1.0);
  414. v_uv = a_pos;
  415. }
  416. )";
  417. static const char *kTexFrag = R"(
  418. #version 330 core
  419. in vec2 v_uv;
  420. uniform sampler2D u_tex;
  421. uniform float u_alpha;
  422. out vec4 fragColor;
  423. void main() {
  424. vec2 uv = vec2(v_uv.x, 1.0 - v_uv.y);
  425. vec4 texel = texture(u_tex, uv);
  426. fragColor = vec4(texel.rgb, texel.a * u_alpha);
  427. }
  428. )";
  429. static const char *kLineVert = R"(
  430. #version 330 core
  431. layout(location = 0) in vec2 a_pos;
  432. uniform mat4 u_mvp;
  433. uniform float u_z;
  434. void main() {
  435. vec3 world = vec3(1.0 - a_pos.x, u_z, a_pos.y);
  436. gl_Position = u_mvp * vec4(world, 1.0);
  437. }
  438. )";
  439. static const char *kLineFrag = R"(
  440. #version 330 core
  441. uniform vec4 u_color;
  442. out vec4 fragColor;
  443. void main() {
  444. fragColor = u_color;
  445. }
  446. )";
  447. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  448. kTexVert)) {
  449. qWarning()
  450. << "CampaignMapRenderer: Failed to compile texture vertex shader";
  451. return false;
  452. }
  453. if (!m_texture_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  454. kTexFrag)) {
  455. qWarning()
  456. << "CampaignMapRenderer: Failed to compile texture fragment shader";
  457. return false;
  458. }
  459. if (!m_texture_program.link()) {
  460. qWarning() << "CampaignMapRenderer: Failed to link texture shader";
  461. return false;
  462. }
  463. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  464. kLineVert)) {
  465. qWarning() << "CampaignMapRenderer: Failed to compile line vertex shader";
  466. return false;
  467. }
  468. if (!m_line_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  469. kLineFrag)) {
  470. qWarning()
  471. << "CampaignMapRenderer: Failed to compile line fragment shader";
  472. return false;
  473. }
  474. if (!m_line_program.link()) {
  475. qWarning() << "CampaignMapRenderer: Failed to link line shader";
  476. return false;
  477. }
  478. init_terrain_shader();
  479. return true;
  480. }
  481. void init_terrain_shader() {
  482. const QString vert_path = Utils::Resources::resolveResourcePath(
  483. QStringLiteral(":/assets/shaders/campaign_terrain.vert"));
  484. const QString frag_path = Utils::Resources::resolveResourcePath(
  485. QStringLiteral(":/assets/shaders/campaign_terrain.frag"));
  486. if (!m_terrain_program.addShaderFromSourceFile(QOpenGLShader::Vertex,
  487. vert_path)) {
  488. qWarning() << "CampaignMapRenderer: Failed to compile terrain vertex"
  489. << vert_path;
  490. m_terrain_program.removeAllShaders();
  491. return;
  492. }
  493. if (!m_terrain_program.addShaderFromSourceFile(QOpenGLShader::Fragment,
  494. frag_path)) {
  495. qWarning() << "CampaignMapRenderer: Failed to compile terrain fragment"
  496. << frag_path;
  497. m_terrain_program.removeAllShaders();
  498. return;
  499. }
  500. if (!m_terrain_program.link()) {
  501. qWarning() << "CampaignMapRenderer: Failed to link terrain shader";
  502. m_terrain_program.removeAllShaders();
  503. }
  504. }
  505. void init_quad() {
  506. if (m_quad_vao != 0) {
  507. return;
  508. }
  509. static const float kQuadVerts[] = {
  510. 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F,
  511. };
  512. glGenVertexArrays(1, &m_quad_vao);
  513. glGenBuffers(1, &m_quad_vbo);
  514. glBindVertexArray(m_quad_vao);
  515. glBindBuffer(GL_ARRAY_BUFFER, m_quad_vbo);
  516. glBufferData(GL_ARRAY_BUFFER, sizeof(kQuadVerts), kQuadVerts,
  517. GL_STATIC_DRAW);
  518. glEnableVertexAttribArray(0);
  519. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  520. reinterpret_cast<void *>(0));
  521. glBindVertexArray(0);
  522. }
  523. void init_land_mesh() {
  524. const QString path = Utils::Resources::resolveResourcePath(
  525. QStringLiteral(":/assets/campaign_map/land_mesh.bin"));
  526. QFile file(path);
  527. if (!file.open(QIODevice::ReadOnly)) {
  528. qWarning() << "CampaignMapRenderer: Failed to open land mesh" << path;
  529. return;
  530. }
  531. const QByteArray data = file.readAll();
  532. if (data.isEmpty() || (data.size() % sizeof(float) != 0)) {
  533. qWarning() << "CampaignMapRenderer: Land mesh is empty or invalid";
  534. return;
  535. }
  536. const int floatCount = data.size() / static_cast<int>(sizeof(float));
  537. if (floatCount % 2 != 0) {
  538. qWarning() << "CampaignMapRenderer: Land mesh float count is odd";
  539. return;
  540. }
  541. std::vector<float> verts(static_cast<size_t>(floatCount));
  542. memcpy(verts.data(), data.constData(), static_cast<size_t>(data.size()));
  543. m_land_vertex_count = floatCount / 2;
  544. if (m_land_vertex_count == 0) {
  545. return;
  546. }
  547. glGenVertexArrays(1, &m_land_vao);
  548. glGenBuffers(1, &m_land_vbo);
  549. glBindVertexArray(m_land_vao);
  550. glBindBuffer(GL_ARRAY_BUFFER, m_land_vbo);
  551. glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(data.size()),
  552. verts.data(), GL_STATIC_DRAW);
  553. glEnableVertexAttribArray(0);
  554. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  555. reinterpret_cast<void *>(0));
  556. glBindVertexArray(0);
  557. }
  558. void init_line_layer(LineLayer &layer, const QString &resource_path,
  559. const QVector4D &color, float width) {
  560. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  561. QFile file(path);
  562. if (!file.open(QIODevice::ReadOnly)) {
  563. qWarning() << "CampaignMapRenderer: Failed to open line layer" << path;
  564. return;
  565. }
  566. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  567. if (!doc.isObject()) {
  568. qWarning() << "CampaignMapRenderer: Line layer JSON invalid" << path;
  569. return;
  570. }
  571. const QJsonArray lines = doc.object().value("lines").toArray();
  572. std::vector<float> verts;
  573. verts.reserve(lines.size() * 8);
  574. std::vector<LineSpan> spans;
  575. int cursor = 0;
  576. for (const auto &line_val : lines) {
  577. const QJsonArray line = line_val.toArray();
  578. if (line.isEmpty()) {
  579. continue;
  580. }
  581. const int start = cursor;
  582. int count = 0;
  583. for (const auto &pt_val : line) {
  584. const QJsonArray pt = pt_val.toArray();
  585. if (pt.size() < 2) {
  586. continue;
  587. }
  588. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  589. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  590. ++count;
  591. ++cursor;
  592. }
  593. if (count >= 2) {
  594. spans.push_back({start, count});
  595. }
  596. }
  597. if (verts.empty() || spans.empty()) {
  598. return;
  599. }
  600. glGenVertexArrays(1, &layer.vao);
  601. glGenBuffers(1, &layer.vbo);
  602. glBindVertexArray(layer.vao);
  603. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  604. glBufferData(GL_ARRAY_BUFFER,
  605. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  606. verts.data(), GL_STATIC_DRAW);
  607. glEnableVertexAttribArray(0);
  608. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  609. reinterpret_cast<void *>(0));
  610. glBindVertexArray(0);
  611. layer.color = color;
  612. layer.width = width;
  613. layer.spans = std::move(spans);
  614. layer.ready = true;
  615. }
  616. void init_province_layer(ProvinceLayer &layer, const QString &resource_path) {
  617. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  618. QFile file(path);
  619. if (!file.open(QIODevice::ReadOnly)) {
  620. qWarning() << "CampaignMapRenderer: Failed to open provinces" << path;
  621. return;
  622. }
  623. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  624. if (!doc.isObject()) {
  625. qWarning() << "CampaignMapRenderer: Provinces JSON invalid" << path;
  626. return;
  627. }
  628. const QJsonArray provinces = doc.object().value("provinces").toArray();
  629. if (provinces.isEmpty()) {
  630. return;
  631. }
  632. std::vector<float> verts;
  633. std::vector<ProvinceSpan> spans;
  634. int cursor = 0;
  635. for (const auto &prov_val : provinces) {
  636. const QJsonObject prov = prov_val.toObject();
  637. const QString province_id = prov.value("id").toString();
  638. const QJsonArray tri = prov.value("triangles").toArray();
  639. if (tri.isEmpty()) {
  640. continue;
  641. }
  642. const int start = cursor;
  643. int count = 0;
  644. for (const auto &pt_val : tri) {
  645. const QJsonArray pt = pt_val.toArray();
  646. if (pt.size() < 2) {
  647. continue;
  648. }
  649. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  650. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  651. ++count;
  652. ++cursor;
  653. }
  654. if (count >= 3) {
  655. QVector4D color(0.0F, 0.0F, 0.0F, 0.0F);
  656. const QJsonArray color_arr = prov.value("color").toArray();
  657. if (color_arr.size() >= 4) {
  658. color = QVector4D(static_cast<float>(color_arr.at(0).toDouble()),
  659. static_cast<float>(color_arr.at(1).toDouble()),
  660. static_cast<float>(color_arr.at(2).toDouble()),
  661. static_cast<float>(color_arr.at(3).toDouble()));
  662. }
  663. spans.push_back({start, count, color, color, province_id});
  664. }
  665. }
  666. if (verts.empty() || spans.empty()) {
  667. return;
  668. }
  669. glGenVertexArrays(1, &layer.vao);
  670. glGenBuffers(1, &layer.vbo);
  671. glBindVertexArray(layer.vao);
  672. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  673. glBufferData(GL_ARRAY_BUFFER,
  674. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  675. verts.data(), GL_STATIC_DRAW);
  676. glEnableVertexAttribArray(0);
  677. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  678. reinterpret_cast<void *>(0));
  679. glBindVertexArray(0);
  680. layer.spans = std::move(spans);
  681. layer.ready = true;
  682. }
  683. void init_borders_layer(LineLayer &layer, const QString &resource_path,
  684. const QVector4D &color, float width) {
  685. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  686. QFile file(path);
  687. if (!file.open(QIODevice::ReadOnly)) {
  688. qWarning() << "CampaignMapRenderer: Failed to open borders" << path;
  689. return;
  690. }
  691. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  692. if (!doc.isObject()) {
  693. qWarning() << "CampaignMapRenderer: Borders JSON invalid" << path;
  694. return;
  695. }
  696. const QJsonArray lines = doc.object().value("borders").toArray();
  697. std::vector<float> verts;
  698. verts.reserve(lines.size() * 8);
  699. std::vector<LineSpan> spans;
  700. int cursor = 0;
  701. for (const auto &line_val : lines) {
  702. const QJsonArray line = line_val.toArray();
  703. if (line.isEmpty()) {
  704. continue;
  705. }
  706. const int start = cursor;
  707. int count = 0;
  708. for (const auto &pt_val : line) {
  709. const QJsonArray pt = pt_val.toArray();
  710. if (pt.size() < 2) {
  711. continue;
  712. }
  713. verts.push_back(static_cast<float>(pt.at(0).toDouble()));
  714. verts.push_back(static_cast<float>(pt.at(1).toDouble()));
  715. ++count;
  716. ++cursor;
  717. }
  718. if (count >= 2) {
  719. spans.push_back({start, count});
  720. }
  721. }
  722. if (verts.empty() || spans.empty()) {
  723. return;
  724. }
  725. glGenVertexArrays(1, &layer.vao);
  726. glGenBuffers(1, &layer.vbo);
  727. glBindVertexArray(layer.vao);
  728. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  729. glBufferData(GL_ARRAY_BUFFER,
  730. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  731. verts.data(), GL_STATIC_DRAW);
  732. glEnableVertexAttribArray(0);
  733. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  734. reinterpret_cast<void *>(0));
  735. glBindVertexArray(0);
  736. layer.color = color;
  737. layer.width = width;
  738. layer.spans = std::move(spans);
  739. layer.ready = true;
  740. }
  741. void init_path_layer(PathLayer &layer, const QString &resource_path) {
  742. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  743. QFile file(path);
  744. if (!file.open(QIODevice::ReadOnly)) {
  745. qWarning() << "CampaignMapRenderer: Failed to open path layer" << path;
  746. return;
  747. }
  748. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  749. if (!doc.isObject()) {
  750. qWarning() << "CampaignMapRenderer: Path layer JSON invalid" << path;
  751. return;
  752. }
  753. const QJsonArray lines = doc.object().value("lines").toArray();
  754. for (const auto &line_val : lines) {
  755. const QJsonArray line = line_val.toArray();
  756. if (line.isEmpty()) {
  757. continue;
  758. }
  759. std::vector<QVector2D> raw_points;
  760. raw_points.reserve(static_cast<size_t>(line.size()));
  761. for (const auto &pt_val : line) {
  762. const QJsonArray pt = pt_val.toArray();
  763. if (pt.size() < 2) {
  764. continue;
  765. }
  766. raw_points.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  767. static_cast<float>(pt.at(1).toDouble()));
  768. }
  769. if (raw_points.size() < 2) {
  770. continue;
  771. }
  772. PathLine entry;
  773. constexpr int k_spline_samples_per_segment = 8;
  774. entry.points = CampaignMapRender::smooth_catmull_rom(
  775. raw_points, k_spline_samples_per_segment);
  776. if (entry.points.size() >= 2) {
  777. layer.lines.push_back(std::move(entry));
  778. }
  779. }
  780. layer.ready = !layer.lines.empty();
  781. }
  782. void init_symbol_layer(CartographicSymbolLayer &layer,
  783. const QString &resource_path) {
  784. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  785. QFile file(path);
  786. if (!file.open(QIODevice::ReadOnly)) {
  787. qWarning() << "CampaignMapRenderer: Failed to open symbols source"
  788. << path;
  789. return;
  790. }
  791. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  792. if (!doc.isObject()) {
  793. qWarning() << "CampaignMapRenderer: Symbols JSON invalid" << path;
  794. return;
  795. }
  796. const QJsonArray provinces = doc.object().value("provinces").toArray();
  797. for (const auto &prov_val : provinces) {
  798. const QJsonObject prov = prov_val.toObject();
  799. const QJsonArray cities = prov.value("cities").toArray();
  800. for (const auto &city_val : cities) {
  801. const QJsonObject city = city_val.toObject();
  802. const QJsonArray uv = city.value("uv").toArray();
  803. if (uv.size() < 2) {
  804. continue;
  805. }
  806. CartographicSymbolInstance symbol;
  807. symbol.position = QVector2D(static_cast<float>(uv.at(0).toDouble()),
  808. static_cast<float>(uv.at(1).toDouble()));
  809. const QString name = city.value("name").toString().toLower();
  810. const bool is_port = name.contains("port") || name.contains("harbor") ||
  811. city.value("is_port").toBool();
  812. const bool is_capital = city.value("is_capital").toBool();
  813. if (is_port) {
  814. symbol.symbol_type = 2;
  815. symbol.importance = 2;
  816. } else if (is_capital) {
  817. symbol.symbol_type = 1;
  818. symbol.importance = 3;
  819. } else {
  820. symbol.symbol_type = 1;
  821. symbol.importance = 1;
  822. }
  823. symbol.size = 0.012F + 0.004F * static_cast<float>(symbol.importance);
  824. layer.symbols.push_back(symbol);
  825. }
  826. const QString terrain = prov.value("terrain_type").toString().toLower();
  827. if (terrain.contains("mountain") || terrain.contains("alpine")) {
  828. const QJsonArray label_uv = prov.value("label_uv").toArray();
  829. if (label_uv.size() >= 2) {
  830. CartographicSymbolInstance mountain;
  831. mountain.position =
  832. QVector2D(static_cast<float>(label_uv.at(0).toDouble()),
  833. static_cast<float>(label_uv.at(1).toDouble()));
  834. mountain.symbol_type = 0;
  835. mountain.importance = 2;
  836. mountain.size = 0.018F;
  837. layer.symbols.push_back(mountain);
  838. }
  839. }
  840. }
  841. if (!layer.symbols.empty()) {
  842. build_symbol_geometry(layer);
  843. }
  844. }
  845. void build_symbol_geometry(CartographicSymbolLayer &layer) {
  846. std::vector<float> verts;
  847. verts.reserve(layer.symbols.size() * 20 * 4);
  848. layer.spans.clear();
  849. for (const auto &symbol : layer.symbols) {
  850. std::vector<QVector2D> outline;
  851. switch (symbol.symbol_type) {
  852. case 0:
  853. outline = CampaignMapRender::generate_mountain_icon(
  854. QVector2D(0.0F, 0.0F), 1.0F, symbol.importance);
  855. break;
  856. case 1:
  857. outline = CampaignMapRender::generate_city_marker(
  858. QVector2D(0.0F, 0.0F), 1.0F, symbol.importance);
  859. break;
  860. case 2:
  861. outline = CampaignMapRender::generate_anchor_icon(QVector2D(0.0F, 0.0F),
  862. 1.0F);
  863. break;
  864. default:
  865. outline = CampaignMapRender::generate_city_marker(QVector2D(0.0F, 0.0F),
  866. 1.0F, 1);
  867. break;
  868. }
  869. if (outline.size() < 2) {
  870. continue;
  871. }
  872. const int start = static_cast<int>(verts.size() / 4);
  873. const int count = static_cast<int>(outline.size());
  874. for (const auto &pt : outline) {
  875. float world_x = symbol.position.x() + pt.x() * symbol.size;
  876. float world_y = symbol.position.y() + pt.y() * symbol.size;
  877. verts.push_back(world_x);
  878. verts.push_back(world_y);
  879. verts.push_back(pt.x());
  880. verts.push_back(static_cast<float>(symbol.symbol_type));
  881. }
  882. layer.spans.push_back({start, count});
  883. }
  884. if (verts.empty() || layer.spans.empty()) {
  885. layer.ready = false;
  886. return;
  887. }
  888. if (layer.vao == 0) {
  889. glGenVertexArrays(1, &layer.vao);
  890. glGenBuffers(1, &layer.vbo);
  891. }
  892. glBindVertexArray(layer.vao);
  893. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  894. glBufferData(GL_ARRAY_BUFFER,
  895. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  896. verts.data(), GL_STATIC_DRAW);
  897. glEnableVertexAttribArray(0);
  898. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  899. reinterpret_cast<void *>(0));
  900. glEnableVertexAttribArray(1);
  901. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  902. reinterpret_cast<void *>(2 * sizeof(float)));
  903. glBindVertexArray(0);
  904. layer.total_vertices = static_cast<int>(verts.size() / 4);
  905. layer.ready = true;
  906. }
  907. void draw_symbol_layer(const CartographicSymbolLayer &layer,
  908. const QMatrix4x4 &mvp, float z_offset) {
  909. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  910. return;
  911. }
  912. m_line_program.bind();
  913. m_line_program.setUniformValue("u_mvp", mvp);
  914. if (layer.show_shadow) {
  915. m_line_program.setUniformValue("u_z", z_offset);
  916. m_line_program.setUniformValue("u_color", layer.shadow_color);
  917. glBindVertexArray(layer.vao);
  918. for (const auto &span : layer.spans) {
  919. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  920. }
  921. glBindVertexArray(0);
  922. }
  923. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  924. m_line_program.setUniformValue("u_color", layer.fill_color);
  925. glBindVertexArray(layer.vao);
  926. for (const auto &span : layer.spans) {
  927. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  928. }
  929. glBindVertexArray(0);
  930. m_line_program.setUniformValue("u_z", z_offset + 0.002F);
  931. m_line_program.setUniformValue("u_color", layer.stroke_color);
  932. glBindVertexArray(layer.vao);
  933. for (const auto &span : layer.spans) {
  934. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  935. }
  936. glBindVertexArray(0);
  937. m_line_program.release();
  938. }
  939. void init_terrain_mesh(TerrainMesh &mesh, int resolution) {
  940. constexpr float k_height_scale = 1.0F;
  941. std::vector<float> vertices;
  942. HeightmapData heightmap = load_heightmap_data(
  943. QStringLiteral(":/assets/campaign_map/terrain_height.png"),
  944. QStringLiteral(":/assets/campaign_map/terrain_height.json"));
  945. if (heightmap.ready) {
  946. const QString land_path = Utils::Resources::resolveResourcePath(
  947. QStringLiteral(":/assets/campaign_map/land_mesh.bin"));
  948. QFile land_file(land_path);
  949. std::vector<float> land_uvs;
  950. if (land_file.open(QIODevice::ReadOnly)) {
  951. const QByteArray data = land_file.readAll();
  952. if (!data.isEmpty() && (data.size() % sizeof(float) == 0)) {
  953. const int float_count =
  954. data.size() / static_cast<int>(sizeof(float));
  955. if (float_count % 2 == 0) {
  956. land_uvs.resize(static_cast<size_t>(float_count));
  957. memcpy(land_uvs.data(), data.constData(),
  958. static_cast<size_t>(data.size()));
  959. }
  960. }
  961. }
  962. if (!land_uvs.empty()) {
  963. mesh.height_scale = k_height_scale;
  964. const float sample_dist =
  965. 1.0F / static_cast<float>(qMax(heightmap.width, heightmap.height));
  966. auto sample_height = [&](float u, float v) -> float {
  967. const float cu = qBound(0.0F, u, 1.0F);
  968. const float cv = qBound(0.0F, v, 1.0F);
  969. const float x = cu * static_cast<float>(heightmap.width - 1);
  970. const float y =
  971. (1.0F - cv) * static_cast<float>(heightmap.height - 1);
  972. const int x0 = static_cast<int>(std::floor(x));
  973. const int y0 = static_cast<int>(std::floor(y));
  974. const int x1 = qMin(x0 + 1, heightmap.width - 1);
  975. const int y1 = qMin(y0 + 1, heightmap.height - 1);
  976. const float fx = x - static_cast<float>(x0);
  977. const float fy = y - static_cast<float>(y0);
  978. const float h00 =
  979. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x0)];
  980. const float h10 =
  981. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x1)];
  982. const float h01 =
  983. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x0)];
  984. const float h11 =
  985. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x1)];
  986. const float hx0 = h00 + (h10 - h00) * fx;
  987. const float hx1 = h01 + (h11 - h01) * fx;
  988. return hx0 + (hx1 - hx0) * fy;
  989. };
  990. auto sample_normal = [&](float u, float v) -> QVector3D {
  991. const float h_left = sample_height(u - sample_dist, v);
  992. const float h_right = sample_height(u + sample_dist, v);
  993. const float h_down = sample_height(u, v - sample_dist);
  994. const float h_up = sample_height(u, v + sample_dist);
  995. const float dx =
  996. (h_right - h_left) / (2.0F * sample_dist) * mesh.height_scale;
  997. const float dz =
  998. (h_up - h_down) / (2.0F * sample_dist) * mesh.height_scale;
  999. QVector3D normal(-dx, 1.0F, -dz);
  1000. normal.normalize();
  1001. return normal;
  1002. };
  1003. vertices.reserve(land_uvs.size() / 2 * 8);
  1004. for (size_t i = 0; i + 1 < land_uvs.size(); i += 2) {
  1005. const float u = land_uvs[i];
  1006. const float v = land_uvs[i + 1];
  1007. const float h = sample_height(u, v);
  1008. const QVector3D n = sample_normal(u, v);
  1009. vertices.push_back(u);
  1010. vertices.push_back(v);
  1011. vertices.push_back(u);
  1012. vertices.push_back(v);
  1013. vertices.push_back(h);
  1014. vertices.push_back(n.x());
  1015. vertices.push_back(n.y());
  1016. vertices.push_back(n.z());
  1017. }
  1018. }
  1019. }
  1020. if (vertices.empty()) {
  1021. mesh.height_scale = k_height_scale;
  1022. vertices = CampaignMapRender::generate_terrain_mesh(resolution, 1.0F);
  1023. }
  1024. if (vertices.empty()) {
  1025. mesh.ready = false;
  1026. return;
  1027. }
  1028. if (mesh.vao == 0) {
  1029. glGenVertexArrays(1, &mesh.vao);
  1030. glGenBuffers(1, &mesh.vbo);
  1031. }
  1032. glBindVertexArray(mesh.vao);
  1033. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1034. glBufferData(GL_ARRAY_BUFFER,
  1035. static_cast<GLsizeiptr>(vertices.size() * sizeof(float)),
  1036. vertices.data(), GL_STATIC_DRAW);
  1037. const int stride = 8 * sizeof(float);
  1038. glEnableVertexAttribArray(0);
  1039. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1040. reinterpret_cast<void *>(0));
  1041. glEnableVertexAttribArray(1);
  1042. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1043. reinterpret_cast<void *>(2 * sizeof(float)));
  1044. glEnableVertexAttribArray(2);
  1045. glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, stride,
  1046. reinterpret_cast<void *>(4 * sizeof(float)));
  1047. glEnableVertexAttribArray(3);
  1048. glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride,
  1049. reinterpret_cast<void *>(5 * sizeof(float)));
  1050. glBindVertexArray(0);
  1051. mesh.vertex_count = static_cast<int>(vertices.size() / 8);
  1052. mesh.ready = true;
  1053. }
  1054. void init_hillshade_layer(HillshadeLayer &layer, int width, int height) {
  1055. CampaignMapRender::HillshadeConfig config;
  1056. config.light_direction = layer.light_direction;
  1057. config.ambient = layer.ambient;
  1058. config.intensity = layer.intensity;
  1059. std::vector<unsigned char> pixels =
  1060. CampaignMapRender::generate_hillshade_texture(width, height, config);
  1061. if (pixels.empty()) {
  1062. layer.ready = false;
  1063. return;
  1064. }
  1065. if (layer.texture_id == 0) {
  1066. glGenTextures(1, &layer.texture_id);
  1067. }
  1068. glBindTexture(GL_TEXTURE_2D, layer.texture_id);
  1069. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
  1070. GL_UNSIGNED_BYTE, pixels.data());
  1071. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1072. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1073. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  1074. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  1075. glBindTexture(GL_TEXTURE_2D, 0);
  1076. layer.width = width;
  1077. layer.height = height;
  1078. layer.ready = true;
  1079. }
  1080. auto load_heightmap_data(const QString &image_path,
  1081. const QString &meta_path) -> HeightmapData {
  1082. HeightmapData data;
  1083. const QString resolved_image =
  1084. Utils::Resources::resolveResourcePath(image_path);
  1085. QImage image(resolved_image);
  1086. if (image.isNull()) {
  1087. qWarning() << "CampaignMapRenderer: Failed to load heightmap"
  1088. << resolved_image;
  1089. return data;
  1090. }
  1091. if (image.format() != QImage::Format_Grayscale16) {
  1092. image = image.convertToFormat(QImage::Format_Grayscale16);
  1093. }
  1094. if (image.isNull()) {
  1095. qWarning() << "CampaignMapRenderer: Heightmap conversion failed"
  1096. << resolved_image;
  1097. return data;
  1098. }
  1099. float min_m = -6000.0F;
  1100. float max_m = 4000.0F;
  1101. const QString resolved_meta =
  1102. Utils::Resources::resolveResourcePath(meta_path);
  1103. QFile meta_file(resolved_meta);
  1104. if (meta_file.open(QIODevice::ReadOnly)) {
  1105. const QJsonDocument doc = QJsonDocument::fromJson(meta_file.readAll());
  1106. if (doc.isObject()) {
  1107. const QJsonObject obj = doc.object();
  1108. if (obj.contains("min_m")) {
  1109. min_m = static_cast<float>(obj.value("min_m").toDouble());
  1110. }
  1111. if (obj.contains("max_m")) {
  1112. max_m = static_cast<float>(obj.value("max_m").toDouble());
  1113. }
  1114. }
  1115. }
  1116. if (!(min_m < max_m)) {
  1117. qWarning() << "CampaignMapRenderer: Heightmap metadata invalid"
  1118. << resolved_meta;
  1119. return data;
  1120. }
  1121. const int width = image.width();
  1122. const int height = image.height();
  1123. if (width <= 1 || height <= 1) {
  1124. qWarning() << "CampaignMapRenderer: Heightmap dimensions invalid"
  1125. << width << height;
  1126. return data;
  1127. }
  1128. const float range = max_m - min_m;
  1129. const float max_abs = qMax(std::abs(min_m), std::abs(max_m));
  1130. if (max_abs <= 0.0F) {
  1131. return data;
  1132. }
  1133. data.samples.resize(static_cast<size_t>(width * height));
  1134. for (int y = 0; y < height; ++y) {
  1135. const auto *row =
  1136. reinterpret_cast<const quint16 *>(image.constScanLine(y));
  1137. for (int x = 0; x < width; ++x) {
  1138. const float norm = static_cast<float>(row[x]) / 65535.0F;
  1139. const float height_m = min_m + norm * range;
  1140. data.samples[static_cast<size_t>(y * width + x)] =
  1141. height_m / max_abs;
  1142. }
  1143. }
  1144. data.width = width;
  1145. data.height = height;
  1146. data.min_m = min_m;
  1147. data.max_m = max_m;
  1148. data.ready = true;
  1149. return data;
  1150. }
  1151. void init_label_layer(LabelLayer &layer, const QString &resource_path) {
  1152. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1153. QFile file(path);
  1154. if (!file.open(QIODevice::ReadOnly)) {
  1155. qWarning() << "CampaignMapRenderer: Failed to open labels source" << path;
  1156. return;
  1157. }
  1158. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1159. if (!doc.isObject()) {
  1160. qWarning() << "CampaignMapRenderer: Labels JSON invalid" << path;
  1161. return;
  1162. }
  1163. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1164. for (const auto &prov_val : provinces) {
  1165. const QJsonObject prov = prov_val.toObject();
  1166. const QString name = prov.value("name").toString();
  1167. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1168. if (name.isEmpty() || label_uv.size() < 2) {
  1169. continue;
  1170. }
  1171. ProvinceLabel label;
  1172. label.text = name;
  1173. label.position = QVector2D(static_cast<float>(label_uv.at(0).toDouble()),
  1174. static_cast<float>(label_uv.at(1).toDouble()));
  1175. const QString id = prov.value("id").toString().toLower();
  1176. if (id.contains("core") || id.contains("capital")) {
  1177. label.importance = 3;
  1178. } else if (id.contains("major") ||
  1179. prov.value("cities").toArray().size() > 2) {
  1180. label.importance = 2;
  1181. } else {
  1182. label.importance = 1;
  1183. }
  1184. label.is_sea = id.contains("sea") || id.contains("mare") ||
  1185. id.contains("mediterranean");
  1186. layer.labels.push_back(label);
  1187. }
  1188. build_label_geometry(layer);
  1189. }
  1190. void build_label_geometry(LabelLayer &layer) {
  1191. std::vector<float> verts;
  1192. for (const auto &label : layer.labels) {
  1193. CampaignMapRender::LabelStyle style;
  1194. if (label.is_sea) {
  1195. style = CampaignMapRender::LabelStyles::sea_label();
  1196. } else if (label.importance >= 3) {
  1197. style = CampaignMapRender::LabelStyles::region_label();
  1198. } else if (label.importance >= 2) {
  1199. style = CampaignMapRender::LabelStyles::province_label();
  1200. } else {
  1201. style = CampaignMapRender::LabelStyles::city_label();
  1202. }
  1203. std::vector<float> label_verts = CampaignMapRender::generate_label_quads(
  1204. label.position, label.text.toStdString(), style);
  1205. verts.insert(verts.end(), label_verts.begin(), label_verts.end());
  1206. }
  1207. if (verts.empty()) {
  1208. layer.ready = false;
  1209. return;
  1210. }
  1211. if (layer.vao == 0) {
  1212. glGenVertexArrays(1, &layer.vao);
  1213. glGenBuffers(1, &layer.vbo);
  1214. }
  1215. glBindVertexArray(layer.vao);
  1216. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  1217. glBufferData(GL_ARRAY_BUFFER,
  1218. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1219. verts.data(), GL_STATIC_DRAW);
  1220. const int stride = 6 * sizeof(float);
  1221. glEnableVertexAttribArray(0);
  1222. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1223. reinterpret_cast<void *>(0));
  1224. glEnableVertexAttribArray(1);
  1225. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1226. reinterpret_cast<void *>(2 * sizeof(float)));
  1227. glEnableVertexAttribArray(2);
  1228. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
  1229. reinterpret_cast<void *>(4 * sizeof(float)));
  1230. glBindVertexArray(0);
  1231. layer.total_vertices = static_cast<int>(verts.size() / 6);
  1232. layer.ready = true;
  1233. }
  1234. void draw_label_layer(const LabelLayer &layer, const QMatrix4x4 &mvp,
  1235. float z_offset) {
  1236. if (!layer.ready || layer.vao == 0 || layer.total_vertices <= 0) {
  1237. return;
  1238. }
  1239. if (layer.font_texture == 0) {
  1240. return;
  1241. }
  1242. m_line_program.bind();
  1243. m_line_program.setUniformValue("u_mvp", mvp);
  1244. m_line_program.setUniformValue("u_z", z_offset);
  1245. m_line_program.setUniformValue("u_color",
  1246. QVector4D(0.25F, 0.20F, 0.15F, 0.85F));
  1247. glBindVertexArray(layer.vao);
  1248. glDrawArrays(GL_TRIANGLES, 0, layer.total_vertices);
  1249. glBindVertexArray(0);
  1250. m_line_program.release();
  1251. }
  1252. auto load_texture(const QString &resource_path) -> QOpenGLTexture * {
  1253. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1254. QImage image(path);
  1255. if (image.isNull()) {
  1256. qWarning() << "CampaignMapRenderer: Failed to load texture" << path;
  1257. return nullptr;
  1258. }
  1259. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  1260. auto *texture = new QOpenGLTexture(rgba);
  1261. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  1262. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  1263. return texture;
  1264. }
  1265. void compute_mvp(QMatrix4x4 &out_mvp) const {
  1266. out_mvp = build_mvp_matrix(
  1267. static_cast<float>(m_size.width()), static_cast<float>(m_size.height()),
  1268. m_orbit_yaw, m_orbit_pitch, m_orbit_distance, m_pan_u, m_pan_v);
  1269. }
  1270. void draw_textured_layer(QOpenGLTexture *texture, GLuint vao,
  1271. int vertex_count, const QMatrix4x4 &mvp, float alpha,
  1272. float z_offset) {
  1273. if (texture == nullptr || vao == 0 || vertex_count <= 0) {
  1274. return;
  1275. }
  1276. m_texture_program.bind();
  1277. m_texture_program.setUniformValue("u_mvp", mvp);
  1278. m_texture_program.setUniformValue("u_z", z_offset);
  1279. m_texture_program.setUniformValue("u_alpha", alpha);
  1280. m_texture_program.setUniformValue("u_tex", 0);
  1281. glActiveTexture(GL_TEXTURE0);
  1282. texture->bind();
  1283. glBindVertexArray(vao);
  1284. glDrawArrays(GL_TRIANGLES, 0, vertex_count);
  1285. glBindVertexArray(0);
  1286. texture->release();
  1287. m_texture_program.release();
  1288. }
  1289. void draw_terrain_layer(const TerrainMesh &mesh, const QMatrix4x4 &mvp) {
  1290. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0 ||
  1291. m_base_texture == nullptr || !m_terrain_program.isLinked()) {
  1292. return;
  1293. }
  1294. m_terrain_program.bind();
  1295. m_terrain_program.setUniformValue("u_mvp", mvp);
  1296. m_terrain_program.setUniformValue("u_height_scale",
  1297. mesh.height_scale *
  1298. m_terrain_height_scale);
  1299. m_terrain_program.setUniformValue("u_z_base", mesh.z_base);
  1300. m_terrain_program.setUniformValue("u_light_direction",
  1301. QVector3D(0.35F, 0.85F, 0.40F));
  1302. m_terrain_program.setUniformValue("u_ambient_strength", 0.45F);
  1303. m_terrain_program.setUniformValue("u_hillshade_strength", 0.35F);
  1304. m_terrain_program.setUniformValue("u_ao_strength", 0.25F);
  1305. m_terrain_program.setUniformValue("u_use_hillshade", true);
  1306. m_terrain_program.setUniformValue("u_use_parchment", false);
  1307. m_terrain_program.setUniformValue("u_use_lighting", true);
  1308. m_terrain_program.setUniformValue("u_water_deep_color",
  1309. QVector3D(0.10F, 0.22F, 0.30F));
  1310. m_terrain_program.setUniformValue("u_water_shallow_color",
  1311. QVector3D(0.26F, 0.42F, 0.52F));
  1312. m_terrain_program.setUniformValue("u_lowland_tint",
  1313. QVector3D(0.96F, 0.92F, 0.86F));
  1314. m_terrain_program.setUniformValue("u_highland_tint",
  1315. QVector3D(0.82F, 0.74F, 0.64F));
  1316. m_terrain_program.setUniformValue("u_mountain_tint",
  1317. QVector3D(0.70F, 0.62F, 0.55F));
  1318. m_terrain_program.setUniformValue("u_elevation_scale", 1.2F);
  1319. m_terrain_program.setUniformValue("u_base_texture", 0);
  1320. glActiveTexture(GL_TEXTURE0);
  1321. m_base_texture->bind();
  1322. glBindVertexArray(mesh.vao);
  1323. glDrawArrays(GL_TRIANGLES, 0, mesh.vertex_count);
  1324. glBindVertexArray(0);
  1325. m_base_texture->release();
  1326. m_terrain_program.release();
  1327. }
  1328. void draw_line_layer(const LineLayer &layer, const QMatrix4x4 &mvp,
  1329. float z_offset) {
  1330. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1331. return;
  1332. }
  1333. m_line_program.bind();
  1334. m_line_program.setUniformValue("u_mvp", mvp);
  1335. if (layer.double_stroke) {
  1336. glLineWidth(layer.width * layer.outer_width_ratio);
  1337. m_line_program.setUniformValue("u_z", z_offset);
  1338. m_line_program.setUniformValue("u_color", layer.outer_color);
  1339. glBindVertexArray(layer.vao);
  1340. for (const auto &span : layer.spans) {
  1341. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1342. }
  1343. glLineWidth(layer.width * layer.inner_width_ratio);
  1344. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1345. m_line_program.setUniformValue("u_color", layer.inner_color);
  1346. for (const auto &span : layer.spans) {
  1347. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1348. }
  1349. glBindVertexArray(0);
  1350. } else {
  1351. glLineWidth(layer.width);
  1352. m_line_program.setUniformValue("u_z", z_offset);
  1353. m_line_program.setUniformValue("u_color", layer.color);
  1354. glBindVertexArray(layer.vao);
  1355. for (const auto &span : layer.spans) {
  1356. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1357. }
  1358. glBindVertexArray(0);
  1359. }
  1360. m_line_program.release();
  1361. }
  1362. static auto safe_normalized(const QVector2D &v) -> QVector2D {
  1363. const float len = v.length();
  1364. if (len < 1e-5F) {
  1365. return QVector2D(0.0F, 0.0F);
  1366. }
  1367. return v / len;
  1368. }
  1369. static auto perp(const QVector2D &v) -> QVector2D {
  1370. return QVector2D(-v.y(), v.x());
  1371. }
  1372. void build_path_strip(const std::vector<QVector2D> &input, float half_width,
  1373. std::vector<QVector2D> &out) const {
  1374. out.clear();
  1375. if (input.size() < 2 || half_width <= 0.0F) {
  1376. return;
  1377. }
  1378. std::vector<QVector2D> points;
  1379. points.reserve(input.size());
  1380. for (const auto &pt : input) {
  1381. if (points.empty()) {
  1382. points.push_back(pt);
  1383. continue;
  1384. }
  1385. const QVector2D delta = pt - points.back();
  1386. if (QVector2D::dotProduct(delta, delta) > 1e-10F) {
  1387. points.push_back(pt);
  1388. }
  1389. }
  1390. if (points.size() < 2) {
  1391. return;
  1392. }
  1393. out.reserve(points.size() * 2);
  1394. for (size_t i = 0; i < points.size(); ++i) {
  1395. QVector2D offset;
  1396. if (i == 0) {
  1397. const QVector2D dir = safe_normalized(points[1] - points[0]);
  1398. offset = perp(dir) * half_width;
  1399. } else if (i + 1 == points.size()) {
  1400. const QVector2D dir = safe_normalized(points[i] - points[i - 1]);
  1401. offset = perp(dir) * half_width;
  1402. } else {
  1403. QVector2D dir0 = safe_normalized(points[i] - points[i - 1]);
  1404. QVector2D dir1 = safe_normalized(points[i + 1] - points[i]);
  1405. if (dir0.isNull()) {
  1406. dir0 = dir1;
  1407. }
  1408. if (dir1.isNull()) {
  1409. dir1 = dir0;
  1410. }
  1411. const QVector2D n0 = perp(dir0);
  1412. const QVector2D n1 = perp(dir1);
  1413. QVector2D miter = safe_normalized(n0 + n1);
  1414. if (miter.isNull()) {
  1415. miter = n1;
  1416. }
  1417. float denom = QVector2D::dotProduct(miter, n1);
  1418. if (std::abs(denom) < 0.2F) {
  1419. denom = (denom >= 0.0F) ? 0.2F : -0.2F;
  1420. }
  1421. float miter_len = half_width / denom;
  1422. const float max_miter = half_width * 3.0F;
  1423. if (std::abs(miter_len) > max_miter) {
  1424. miter_len = (miter_len < 0.0F) ? -max_miter : max_miter;
  1425. }
  1426. offset = miter * miter_len;
  1427. }
  1428. out.push_back(points[i] + offset);
  1429. out.push_back(points[i] - offset);
  1430. }
  1431. }
  1432. void update_path_mesh(StrokeMesh &mesh, const std::vector<QVector2D> &points,
  1433. float width) {
  1434. if (points.size() < 2) {
  1435. mesh.ready = false;
  1436. mesh.vertex_count = 0;
  1437. return;
  1438. }
  1439. if (mesh.ready && qFuzzyCompare(mesh.width, width)) {
  1440. return;
  1441. }
  1442. CampaignMapRender::StrokeMeshConfig config;
  1443. config.width = width;
  1444. config.start_cap = CampaignMapRender::CapStyle::Round;
  1445. config.end_cap = CampaignMapRender::CapStyle::Round;
  1446. config.join_style = CampaignMapRender::JoinStyle::Miter;
  1447. config.cap_segments = 6;
  1448. config.miter_params.max_miter_ratio = 3.0F;
  1449. std::vector<QVector2D> strip =
  1450. CampaignMapRender::build_stroke_mesh(points, config);
  1451. if (strip.size() < 4) {
  1452. mesh.ready = false;
  1453. mesh.vertex_count = 0;
  1454. return;
  1455. }
  1456. std::vector<float> verts;
  1457. verts.reserve(strip.size() * 2);
  1458. for (const auto &v : strip) {
  1459. verts.push_back(v.x());
  1460. verts.push_back(v.y());
  1461. }
  1462. if (mesh.vao == 0) {
  1463. glGenVertexArrays(1, &mesh.vao);
  1464. glGenBuffers(1, &mesh.vbo);
  1465. }
  1466. glBindVertexArray(mesh.vao);
  1467. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1468. glBufferData(GL_ARRAY_BUFFER,
  1469. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1470. verts.data(), GL_DYNAMIC_DRAW);
  1471. glEnableVertexAttribArray(0);
  1472. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  1473. reinterpret_cast<void *>(0));
  1474. glBindVertexArray(0);
  1475. mesh.vertex_count = static_cast<int>(strip.size());
  1476. mesh.width = width;
  1477. mesh.ready = true;
  1478. }
  1479. auto uv_width_for_pixels(float px) const -> float {
  1480. const float viewport_h = qMax(1.0F, static_cast<float>(m_size.height()));
  1481. const float fov_rad = qDegreesToRadians(45.0F * 0.5F);
  1482. const float view_h = 2.0F * m_orbit_distance * std::tan(fov_rad);
  1483. const float uv_width = px * (view_h / viewport_h);
  1484. return qMax(0.0005F, uv_width);
  1485. }
  1486. void draw_path_mesh(const StrokeMesh &mesh) {
  1487. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0) {
  1488. return;
  1489. }
  1490. glBindVertexArray(mesh.vao);
  1491. glDrawArrays(GL_TRIANGLE_STRIP, 0, mesh.vertex_count);
  1492. glBindVertexArray(0);
  1493. }
  1494. void draw_progressive_path_layers(PathLayer &layer, const QMatrix4x4 &mvp,
  1495. float z_offset) {
  1496. if (!layer.ready || layer.lines.empty()) {
  1497. return;
  1498. }
  1499. const int max_mission =
  1500. qBound(0, m_current_mission, static_cast<int>(layer.lines.size()) - 1);
  1501. m_line_program.bind();
  1502. m_line_program.setUniformValue("u_mvp", mvp);
  1503. for (int i = 0; i <= max_mission; ++i) {
  1504. if (i >= static_cast<int>(layer.lines.size())) {
  1505. break;
  1506. }
  1507. auto &line = layer.lines[static_cast<size_t>(i)];
  1508. const int age = max_mission - i;
  1509. auto passes =
  1510. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1511. age);
  1512. if (!passes.empty()) {
  1513. const auto &border_pass = passes[0];
  1514. float border_width_px = 6.0F * border_pass.width_multiplier;
  1515. if (i != max_mission) {
  1516. border_width_px *= 0.85F;
  1517. }
  1518. m_line_program.setUniformValue("u_z", z_offset + border_pass.z_offset);
  1519. update_path_mesh(line.border, line.points,
  1520. uv_width_for_pixels(border_width_px));
  1521. m_line_program.setUniformValue("u_color", border_pass.color);
  1522. draw_path_mesh(line.border);
  1523. }
  1524. }
  1525. for (int i = 0; i <= max_mission; ++i) {
  1526. if (i >= static_cast<int>(layer.lines.size())) {
  1527. break;
  1528. }
  1529. auto &line = layer.lines[static_cast<size_t>(i)];
  1530. const int age = max_mission - i;
  1531. auto passes =
  1532. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1533. age);
  1534. if (passes.size() > 2) {
  1535. const auto &highlight_pass = passes[2];
  1536. float highlight_width_px = 4.0F * highlight_pass.width_multiplier;
  1537. if (i != max_mission) {
  1538. highlight_width_px *= 0.8F;
  1539. }
  1540. m_line_program.setUniformValue("u_z",
  1541. z_offset + highlight_pass.z_offset);
  1542. update_path_mesh(line.highlight, line.points,
  1543. uv_width_for_pixels(highlight_width_px));
  1544. m_line_program.setUniformValue("u_color", highlight_pass.color);
  1545. draw_path_mesh(line.highlight);
  1546. }
  1547. }
  1548. for (int i = 0; i <= max_mission; ++i) {
  1549. if (i >= static_cast<int>(layer.lines.size())) {
  1550. break;
  1551. }
  1552. auto &line = layer.lines[static_cast<size_t>(i)];
  1553. const int age = max_mission - i;
  1554. auto passes =
  1555. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1556. age);
  1557. if (passes.size() > 3) {
  1558. const auto &core_pass = passes[3];
  1559. float core_width_px = 3.0F * core_pass.width_multiplier;
  1560. if (i != max_mission) {
  1561. core_width_px *= 0.75F;
  1562. }
  1563. m_line_program.setUniformValue("u_z", z_offset + core_pass.z_offset);
  1564. update_path_mesh(line.core, line.points,
  1565. uv_width_for_pixels(core_width_px));
  1566. m_line_program.setUniformValue("u_color", core_pass.color);
  1567. draw_path_mesh(line.core);
  1568. }
  1569. }
  1570. m_line_program.release();
  1571. }
  1572. void update_mission_badge_position(MissionBadge &badge,
  1573. const PathLayer &path_layer,
  1574. int mission_index) {
  1575. if (!path_layer.ready || path_layer.lines.empty()) {
  1576. badge.ready = false;
  1577. return;
  1578. }
  1579. const int clamped_mission =
  1580. qBound(0, mission_index, static_cast<int>(path_layer.lines.size()) - 1);
  1581. const auto &line = path_layer.lines[static_cast<size_t>(clamped_mission)];
  1582. if (line.points.empty()) {
  1583. badge.ready = false;
  1584. return;
  1585. }
  1586. badge.position = line.points.back();
  1587. badge.ready = true;
  1588. }
  1589. void build_badge_geometry(MissionBadge &badge) {
  1590. if (!badge.ready) {
  1591. return;
  1592. }
  1593. std::vector<QVector2D> outline = CampaignMapRender::generate_shield_badge(
  1594. QVector2D(0.0F, 0.0F), 1.0F, 16);
  1595. if (outline.size() < 3) {
  1596. badge.ready = false;
  1597. return;
  1598. }
  1599. std::vector<float> verts;
  1600. verts.reserve((outline.size() + 1) * 4);
  1601. verts.push_back(badge.position.x());
  1602. verts.push_back(badge.position.y());
  1603. verts.push_back(0.0F);
  1604. verts.push_back(0.0F);
  1605. for (const auto &pt : outline) {
  1606. verts.push_back(badge.position.x() + pt.x() * badge.size);
  1607. verts.push_back(badge.position.y() + pt.y() * badge.size);
  1608. verts.push_back(pt.x());
  1609. verts.push_back(pt.y());
  1610. }
  1611. if (badge.vao == 0) {
  1612. glGenVertexArrays(1, &badge.vao);
  1613. glGenBuffers(1, &badge.vbo);
  1614. }
  1615. glBindVertexArray(badge.vao);
  1616. glBindBuffer(GL_ARRAY_BUFFER, badge.vbo);
  1617. glBufferData(GL_ARRAY_BUFFER,
  1618. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1619. verts.data(), GL_DYNAMIC_DRAW);
  1620. glEnableVertexAttribArray(0);
  1621. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1622. reinterpret_cast<void *>(0));
  1623. glEnableVertexAttribArray(1);
  1624. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1625. reinterpret_cast<void *>(2 * sizeof(float)));
  1626. glBindVertexArray(0);
  1627. badge.vertex_count = static_cast<int>(outline.size() + 1);
  1628. }
  1629. void draw_mission_badge(MissionBadge &badge, const QMatrix4x4 &mvp,
  1630. float z_offset) {
  1631. if (!badge.ready) {
  1632. return;
  1633. }
  1634. update_mission_badge_position(badge, m_path_layer, m_current_mission);
  1635. build_badge_geometry(badge);
  1636. if (badge.vao == 0 || badge.vertex_count < 3) {
  1637. return;
  1638. }
  1639. m_line_program.bind();
  1640. m_line_program.setUniformValue("u_mvp", mvp);
  1641. if (badge.show_shadow) {
  1642. m_line_program.setUniformValue("u_z", z_offset);
  1643. m_line_program.setUniformValue("u_color", badge.shadow_color);
  1644. glBindVertexArray(badge.vao);
  1645. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1646. glBindVertexArray(0);
  1647. }
  1648. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1649. m_line_program.setUniformValue("u_color", badge.border_color);
  1650. glBindVertexArray(badge.vao);
  1651. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1652. glBindVertexArray(0);
  1653. m_line_program.setUniformValue("u_z", z_offset + 0.002F);
  1654. m_line_program.setUniformValue("u_color", badge.primary_color);
  1655. glBindVertexArray(badge.vao);
  1656. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1657. glBindVertexArray(0);
  1658. m_line_program.release();
  1659. }
  1660. void apply_province_overrides(
  1661. const QHash<QString, CampaignMapView::ProvinceVisual> &overrides) {
  1662. if (!m_province_layer.ready || m_province_layer.spans.empty()) {
  1663. return;
  1664. }
  1665. for (auto &span : m_province_layer.spans) {
  1666. const auto it = overrides.find(span.id);
  1667. if (it != overrides.end() && it->has_color) {
  1668. span.color = it->color;
  1669. } else {
  1670. span.color = span.base_color;
  1671. }
  1672. }
  1673. }
  1674. void draw_province_layer(const ProvinceLayer &layer, const QMatrix4x4 &mvp,
  1675. float z_offset) {
  1676. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1677. return;
  1678. }
  1679. m_line_program.bind();
  1680. m_line_program.setUniformValue("u_mvp", mvp);
  1681. m_line_program.setUniformValue("u_z", z_offset);
  1682. glBindVertexArray(layer.vao);
  1683. for (const auto &span : layer.spans) {
  1684. if (span.color.w() <= 0.0F) {
  1685. continue;
  1686. }
  1687. QVector4D color = span.color;
  1688. const float parchment_tint = 0.92F;
  1689. color.setX(color.x() * parchment_tint);
  1690. color.setY(color.y() * parchment_tint);
  1691. color.setZ(color.z() * parchment_tint * 0.98F);
  1692. if (m_terrain_mesh.ready && m_terrain_height_scale > 0.01F) {
  1693. float fade = 1.0F / (1.0F + 3.0F * m_terrain_height_scale);
  1694. color.setW(color.w() * fade);
  1695. }
  1696. if (!m_hover_province_id.isEmpty() && span.id == m_hover_province_id) {
  1697. qint64 elapsed =
  1698. QDateTime::currentMSecsSinceEpoch() - m_hover_start_time;
  1699. float pulse_cycle = 1200.0F;
  1700. float pulse =
  1701. 0.5F + 0.5F * std::sin(elapsed * 2.0F * M_PI / pulse_cycle);
  1702. float brightness_boost = 0.3F + 0.15F * pulse;
  1703. color = QVector4D(qMin(1.0F, color.x() + brightness_boost),
  1704. qMin(1.0F, color.y() + brightness_boost),
  1705. qMin(1.0F, color.z() + brightness_boost),
  1706. qMin(1.0F, color.w() + 0.2F));
  1707. }
  1708. m_line_program.setUniformValue("u_color", color);
  1709. glDrawArrays(GL_TRIANGLES, span.start, span.count);
  1710. }
  1711. glBindVertexArray(0);
  1712. m_line_program.release();
  1713. }
  1714. void cleanup() {
  1715. if (QOpenGLContext::currentContext() == nullptr) {
  1716. return;
  1717. }
  1718. if (m_quad_vbo != 0) {
  1719. glDeleteBuffers(1, &m_quad_vbo);
  1720. m_quad_vbo = 0;
  1721. }
  1722. if (m_quad_vao != 0) {
  1723. glDeleteVertexArrays(1, &m_quad_vao);
  1724. m_quad_vao = 0;
  1725. }
  1726. if (m_land_vbo != 0) {
  1727. glDeleteBuffers(1, &m_land_vbo);
  1728. m_land_vbo = 0;
  1729. }
  1730. if (m_land_vao != 0) {
  1731. glDeleteVertexArrays(1, &m_land_vao);
  1732. m_land_vao = 0;
  1733. }
  1734. if (m_coast_layer.vbo != 0) {
  1735. glDeleteBuffers(1, &m_coast_layer.vbo);
  1736. m_coast_layer.vbo = 0;
  1737. }
  1738. if (m_coast_layer.vao != 0) {
  1739. glDeleteVertexArrays(1, &m_coast_layer.vao);
  1740. m_coast_layer.vao = 0;
  1741. }
  1742. if (m_river_layer.vbo != 0) {
  1743. glDeleteBuffers(1, &m_river_layer.vbo);
  1744. m_river_layer.vbo = 0;
  1745. }
  1746. if (m_river_layer.vao != 0) {
  1747. glDeleteVertexArrays(1, &m_river_layer.vao);
  1748. m_river_layer.vao = 0;
  1749. }
  1750. for (auto &line : m_path_layer.lines) {
  1751. if (line.border.vbo != 0) {
  1752. glDeleteBuffers(1, &line.border.vbo);
  1753. line.border.vbo = 0;
  1754. }
  1755. if (line.border.vao != 0) {
  1756. glDeleteVertexArrays(1, &line.border.vao);
  1757. line.border.vao = 0;
  1758. }
  1759. if (line.highlight.vbo != 0) {
  1760. glDeleteBuffers(1, &line.highlight.vbo);
  1761. line.highlight.vbo = 0;
  1762. }
  1763. if (line.highlight.vao != 0) {
  1764. glDeleteVertexArrays(1, &line.highlight.vao);
  1765. line.highlight.vao = 0;
  1766. }
  1767. if (line.core.vbo != 0) {
  1768. glDeleteBuffers(1, &line.core.vbo);
  1769. line.core.vbo = 0;
  1770. }
  1771. if (line.core.vao != 0) {
  1772. glDeleteVertexArrays(1, &line.core.vao);
  1773. line.core.vao = 0;
  1774. }
  1775. }
  1776. m_path_layer.lines.clear();
  1777. if (m_province_border_layer.vbo != 0) {
  1778. glDeleteBuffers(1, &m_province_border_layer.vbo);
  1779. m_province_border_layer.vbo = 0;
  1780. }
  1781. if (m_province_border_layer.vao != 0) {
  1782. glDeleteVertexArrays(1, &m_province_border_layer.vao);
  1783. m_province_border_layer.vao = 0;
  1784. }
  1785. if (m_province_layer.vbo != 0) {
  1786. glDeleteBuffers(1, &m_province_layer.vbo);
  1787. m_province_layer.vbo = 0;
  1788. }
  1789. if (m_province_layer.vao != 0) {
  1790. glDeleteVertexArrays(1, &m_province_layer.vao);
  1791. m_province_layer.vao = 0;
  1792. }
  1793. if (m_mission_badge.vbo != 0) {
  1794. glDeleteBuffers(1, &m_mission_badge.vbo);
  1795. m_mission_badge.vbo = 0;
  1796. }
  1797. if (m_mission_badge.vao != 0) {
  1798. glDeleteVertexArrays(1, &m_mission_badge.vao);
  1799. m_mission_badge.vao = 0;
  1800. }
  1801. m_mission_badge.ready = false;
  1802. if (m_symbol_layer.vbo != 0) {
  1803. glDeleteBuffers(1, &m_symbol_layer.vbo);
  1804. m_symbol_layer.vbo = 0;
  1805. }
  1806. if (m_symbol_layer.vao != 0) {
  1807. glDeleteVertexArrays(1, &m_symbol_layer.vao);
  1808. m_symbol_layer.vao = 0;
  1809. }
  1810. m_symbol_layer.symbols.clear();
  1811. m_symbol_layer.ready = false;
  1812. if (m_terrain_mesh.vbo != 0) {
  1813. glDeleteBuffers(1, &m_terrain_mesh.vbo);
  1814. m_terrain_mesh.vbo = 0;
  1815. }
  1816. if (m_terrain_mesh.vao != 0) {
  1817. glDeleteVertexArrays(1, &m_terrain_mesh.vao);
  1818. m_terrain_mesh.vao = 0;
  1819. }
  1820. m_terrain_mesh.ready = false;
  1821. if (m_hillshade.texture_id != 0) {
  1822. glDeleteTextures(1, &m_hillshade.texture_id);
  1823. m_hillshade.texture_id = 0;
  1824. }
  1825. m_hillshade.ready = false;
  1826. if (m_label_layer.vbo != 0) {
  1827. glDeleteBuffers(1, &m_label_layer.vbo);
  1828. m_label_layer.vbo = 0;
  1829. }
  1830. if (m_label_layer.vao != 0) {
  1831. glDeleteVertexArrays(1, &m_label_layer.vao);
  1832. m_label_layer.vao = 0;
  1833. }
  1834. if (m_label_layer.font_texture != 0) {
  1835. glDeleteTextures(1, &m_label_layer.font_texture);
  1836. m_label_layer.font_texture = 0;
  1837. }
  1838. m_label_layer.labels.clear();
  1839. m_label_layer.ready = false;
  1840. m_base_texture = nullptr;
  1841. m_water_texture = nullptr;
  1842. }
  1843. };
  1844. } // namespace
  1845. CampaignMapView::CampaignMapView() {
  1846. setMirrorVertically(true);
  1847. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  1848. if (ctx == nullptr) {
  1849. qWarning() << "CampaignMapView: No OpenGL context available";
  1850. qWarning()
  1851. << "CampaignMapView: 3D rendering will not work in software mode";
  1852. qWarning()
  1853. << "CampaignMapView: Try running without QT_QUICK_BACKEND=software";
  1854. }
  1855. }
  1856. void CampaignMapView::load_provinces_for_hit_test() {
  1857. if (m_provinces_loaded) {
  1858. return;
  1859. }
  1860. m_provinces_loaded = true;
  1861. m_provinces.clear();
  1862. const QString path = Utils::Resources::resolveResourcePath(
  1863. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1864. QFile file(path);
  1865. if (!file.open(QIODevice::ReadOnly)) {
  1866. return;
  1867. }
  1868. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1869. if (!doc.isObject()) {
  1870. return;
  1871. }
  1872. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1873. for (const auto &prov_val : provinces) {
  1874. const QJsonObject prov = prov_val.toObject();
  1875. const QJsonArray tri = prov.value("triangles").toArray();
  1876. if (tri.isEmpty()) {
  1877. continue;
  1878. }
  1879. ProvinceHit province;
  1880. province.id = prov.value("id").toString();
  1881. province.name = prov.value("name").toString();
  1882. province.owner = prov.value("owner").toString();
  1883. province.triangles.reserve(static_cast<size_t>(tri.size()));
  1884. for (const auto &pt_val : tri) {
  1885. const QJsonArray pt = pt_val.toArray();
  1886. if (pt.size() < 2) {
  1887. continue;
  1888. }
  1889. province.triangles.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  1890. static_cast<float>(pt.at(1).toDouble()));
  1891. }
  1892. if (province.triangles.size() >= 3) {
  1893. m_provinces.push_back(std::move(province));
  1894. }
  1895. }
  1896. if (!m_province_overrides.isEmpty()) {
  1897. for (auto &province : m_provinces) {
  1898. const auto it = m_province_overrides.find(province.id);
  1899. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1900. province.owner = it->owner;
  1901. }
  1902. }
  1903. }
  1904. }
  1905. void CampaignMapView::load_province_labels() {
  1906. if (m_province_labels_loaded) {
  1907. return;
  1908. }
  1909. m_province_labels_loaded = true;
  1910. m_province_labels.clear();
  1911. const QString path = Utils::Resources::resolveResourcePath(
  1912. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1913. QFile file(path);
  1914. if (!file.open(QIODevice::ReadOnly)) {
  1915. return;
  1916. }
  1917. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1918. if (!doc.isObject()) {
  1919. return;
  1920. }
  1921. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1922. for (const auto &prov_val : provinces) {
  1923. const QJsonObject prov = prov_val.toObject();
  1924. QVariantMap entry;
  1925. entry.insert(QStringLiteral("id"), prov.value("id").toString());
  1926. entry.insert(QStringLiteral("name"), prov.value("name").toString());
  1927. entry.insert(QStringLiteral("owner"), prov.value("owner").toString());
  1928. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1929. if (label_uv.size() >= 2) {
  1930. QVariantList label_list;
  1931. label_list.reserve(2);
  1932. label_list.push_back(label_uv.at(0).toDouble());
  1933. label_list.push_back(label_uv.at(1).toDouble());
  1934. entry.insert(QStringLiteral("label_uv"), label_list);
  1935. }
  1936. const QJsonArray cities = prov.value("cities").toArray();
  1937. QVariantList city_list;
  1938. city_list.reserve(cities.size());
  1939. for (const auto &city_val : cities) {
  1940. const QJsonObject city = city_val.toObject();
  1941. const QString name = city.value("name").toString();
  1942. const QJsonArray uv = city.value("uv").toArray();
  1943. if (name.isEmpty() || uv.size() < 2) {
  1944. continue;
  1945. }
  1946. QVariantList uv_list;
  1947. uv_list.reserve(2);
  1948. uv_list.push_back(uv.at(0).toDouble());
  1949. uv_list.push_back(uv.at(1).toDouble());
  1950. QVariantMap city_entry;
  1951. city_entry.insert(QStringLiteral("name"), name);
  1952. city_entry.insert(QStringLiteral("uv"), uv_list);
  1953. city_list.push_back(city_entry);
  1954. }
  1955. entry.insert(QStringLiteral("cities"), city_list);
  1956. m_province_labels.push_back(entry);
  1957. }
  1958. if (!m_province_overrides.isEmpty()) {
  1959. QVariantList updated;
  1960. updated.reserve(m_province_labels.size());
  1961. for (const auto &entry_val : m_province_labels) {
  1962. QVariantMap entry = entry_val.toMap();
  1963. const QString id = entry.value(QStringLiteral("id")).toString();
  1964. const auto it = m_province_overrides.find(id);
  1965. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1966. entry.insert(QStringLiteral("owner"), it->owner);
  1967. }
  1968. updated.push_back(entry);
  1969. }
  1970. m_province_labels = std::move(updated);
  1971. }
  1972. emit province_labels_changed();
  1973. }
  1974. QVariantList CampaignMapView::province_labels() {
  1975. load_province_labels();
  1976. return m_province_labels;
  1977. }
  1978. void CampaignMapView::apply_province_state(const QVariantList &states) {
  1979. QHash<QString, ProvinceVisual> next_overrides;
  1980. next_overrides.reserve(states.size());
  1981. for (const auto &state_val : states) {
  1982. const QVariantMap state = state_val.toMap();
  1983. const QString id = state.value(QStringLiteral("id")).toString();
  1984. if (id.isEmpty()) {
  1985. continue;
  1986. }
  1987. ProvinceVisual visual;
  1988. visual.owner = state.value(QStringLiteral("owner")).toString();
  1989. const QVariantList color_list =
  1990. state.value(QStringLiteral("color")).toList();
  1991. if (color_list.size() >= 4) {
  1992. visual.color = QVector4D(static_cast<float>(color_list.at(0).toDouble()),
  1993. static_cast<float>(color_list.at(1).toDouble()),
  1994. static_cast<float>(color_list.at(2).toDouble()),
  1995. static_cast<float>(color_list.at(3).toDouble()));
  1996. visual.has_color = true;
  1997. }
  1998. next_overrides.insert(id, visual);
  1999. }
  2000. m_province_overrides = std::move(next_overrides);
  2001. ++m_province_state_version;
  2002. if (m_provinces_loaded) {
  2003. for (auto &province : m_provinces) {
  2004. const auto it = m_province_overrides.find(province.id);
  2005. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2006. province.owner = it->owner;
  2007. }
  2008. }
  2009. }
  2010. if (m_province_labels_loaded) {
  2011. QVariantList updated;
  2012. updated.reserve(m_province_labels.size());
  2013. for (const auto &entry_val : m_province_labels) {
  2014. QVariantMap entry = entry_val.toMap();
  2015. const QString id = entry.value(QStringLiteral("id")).toString();
  2016. const auto it = m_province_overrides.find(id);
  2017. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2018. entry.insert(QStringLiteral("owner"), it->owner);
  2019. }
  2020. updated.push_back(entry);
  2021. }
  2022. m_province_labels = std::move(updated);
  2023. emit province_labels_changed();
  2024. }
  2025. update();
  2026. }
  2027. QString CampaignMapView::province_at_screen(float x, float y) {
  2028. load_provinces_for_hit_test();
  2029. if (m_provinces.empty()) {
  2030. return {};
  2031. }
  2032. const float w = static_cast<float>(width());
  2033. const float h = static_cast<float>(height());
  2034. if (w <= 0.0F || h <= 0.0F) {
  2035. return {};
  2036. }
  2037. const float ndc_x = (2.0F * x / w) - 1.0F;
  2038. const float ndc_y = 1.0F - (2.0F * y / h);
  2039. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2040. m_orbit_distance, m_pan_u, m_pan_v);
  2041. bool inverted = false;
  2042. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2043. if (!inverted) {
  2044. return {};
  2045. }
  2046. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2047. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2048. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2049. return {};
  2050. }
  2051. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2052. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2053. const QVector3D dir = far_v - near_v;
  2054. if (qFuzzyIsNull(dir.y())) {
  2055. return {};
  2056. }
  2057. const float t = -near_v.y() / dir.y();
  2058. if (t < 0.0F) {
  2059. return {};
  2060. }
  2061. const QVector3D hit = near_v + dir * t;
  2062. const float u = 1.0F - hit.x();
  2063. const float v = hit.z();
  2064. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2065. return {};
  2066. }
  2067. const QVector2D p(u, v);
  2068. for (const auto &province : m_provinces) {
  2069. const auto &triangles = province.triangles;
  2070. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2071. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2072. triangles[i + 2])) {
  2073. return province.id;
  2074. }
  2075. }
  2076. }
  2077. return {};
  2078. }
  2079. QVariantMap CampaignMapView::province_info_at_screen(float x, float y) {
  2080. load_provinces_for_hit_test();
  2081. QVariantMap info;
  2082. if (m_provinces.empty()) {
  2083. return info;
  2084. }
  2085. const float w = static_cast<float>(width());
  2086. const float h = static_cast<float>(height());
  2087. if (w <= 0.0F || h <= 0.0F) {
  2088. return info;
  2089. }
  2090. const float ndc_x = (2.0F * x / w) - 1.0F;
  2091. const float ndc_y = 1.0F - (2.0F * y / h);
  2092. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2093. m_orbit_distance, m_pan_u, m_pan_v);
  2094. bool inverted = false;
  2095. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2096. if (!inverted) {
  2097. return info;
  2098. }
  2099. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2100. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2101. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2102. return info;
  2103. }
  2104. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2105. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2106. const QVector3D dir = far_v - near_v;
  2107. if (qFuzzyIsNull(dir.y())) {
  2108. return info;
  2109. }
  2110. const float t = -near_v.y() / dir.y();
  2111. if (t < 0.0F) {
  2112. return info;
  2113. }
  2114. const QVector3D hit = near_v + dir * t;
  2115. const float u = 1.0F - hit.x();
  2116. const float v = hit.z();
  2117. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2118. return info;
  2119. }
  2120. const QVector2D p(u, v);
  2121. for (const auto &province : m_provinces) {
  2122. const auto &triangles = province.triangles;
  2123. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2124. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2125. triangles[i + 2])) {
  2126. info.insert(QStringLiteral("id"), province.id);
  2127. info.insert(QStringLiteral("name"), province.name);
  2128. info.insert(QStringLiteral("owner"), province.owner);
  2129. return info;
  2130. }
  2131. }
  2132. }
  2133. return info;
  2134. }
  2135. QPointF CampaignMapView::screen_pos_for_uv(float u, float v) {
  2136. const float w = static_cast<float>(width());
  2137. const float h = static_cast<float>(height());
  2138. if (w <= 0.0F || h <= 0.0F) {
  2139. return {};
  2140. }
  2141. const float clamped_u = qBound(0.0F, u, 1.0F);
  2142. const float clamped_v = qBound(0.0F, v, 1.0F);
  2143. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2144. m_orbit_distance, m_pan_u, m_pan_v);
  2145. const QVector4D world(1.0F - clamped_u, 0.0F, clamped_v, 1.0F);
  2146. const QVector4D clip = mvp * world;
  2147. if (qFuzzyIsNull(clip.w())) {
  2148. return {};
  2149. }
  2150. const float ndc_x = clip.x() / clip.w();
  2151. const float ndc_y = clip.y() / clip.w();
  2152. const float screen_x = (ndc_x + 1.0F) * 0.5F * w;
  2153. const float screen_y = (1.0F - (ndc_y + 1.0F) * 0.5F) * h;
  2154. return QPointF(screen_x, screen_y);
  2155. }
  2156. void CampaignMapView::load_hannibal_paths() {
  2157. if (m_hannibal_paths_loaded) {
  2158. return;
  2159. }
  2160. m_hannibal_paths_loaded = true;
  2161. m_hannibal_paths.clear();
  2162. const QString path = Utils::Resources::resolveResourcePath(
  2163. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  2164. QFile file(path);
  2165. if (!file.open(QIODevice::ReadOnly)) {
  2166. qWarning() << "Failed to load Hannibal paths from" << path;
  2167. return;
  2168. }
  2169. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  2170. if (!doc.isObject()) {
  2171. return;
  2172. }
  2173. const QJsonArray lines = doc.object().value("lines").toArray();
  2174. for (const auto &line_val : lines) {
  2175. const QJsonArray line = line_val.toArray();
  2176. std::vector<QVector2D> path;
  2177. path.reserve(static_cast<size_t>(line.size()));
  2178. for (const auto &pt_val : line) {
  2179. const QJsonArray pt = pt_val.toArray();
  2180. if (pt.size() < 2) {
  2181. continue;
  2182. }
  2183. path.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  2184. static_cast<float>(pt.at(1).toDouble()));
  2185. }
  2186. if (!path.empty()) {
  2187. m_hannibal_paths.push_back(std::move(path));
  2188. }
  2189. }
  2190. }
  2191. QPointF CampaignMapView::hannibal_icon_position() {
  2192. load_hannibal_paths();
  2193. if (m_hannibal_paths.empty()) {
  2194. return {};
  2195. }
  2196. const int mission_idx = qBound(0, m_current_mission,
  2197. static_cast<int>(m_hannibal_paths.size()) - 1);
  2198. const auto &path = m_hannibal_paths[static_cast<size_t>(mission_idx)];
  2199. if (path.empty()) {
  2200. return {};
  2201. }
  2202. const QVector2D &endpoint = path.back();
  2203. return screen_pos_for_uv(endpoint.x(), endpoint.y());
  2204. }
  2205. void CampaignMapView::set_orbit_yaw(float yaw) {
  2206. if (qFuzzyCompare(m_orbit_yaw, yaw)) {
  2207. return;
  2208. }
  2209. m_orbit_yaw = yaw;
  2210. emit orbit_yaw_changed();
  2211. update();
  2212. }
  2213. void CampaignMapView::set_orbit_pitch(float pitch) {
  2214. const float clamped = qBound(5.0F, pitch, 90.0F);
  2215. if (qFuzzyCompare(m_orbit_pitch, clamped)) {
  2216. return;
  2217. }
  2218. m_orbit_pitch = clamped;
  2219. emit orbit_pitch_changed();
  2220. update();
  2221. }
  2222. void CampaignMapView::set_orbit_distance(float distance) {
  2223. const float clamped =
  2224. qBound(k_min_orbit_distance, distance, k_max_orbit_distance);
  2225. if (qFuzzyCompare(m_orbit_distance, clamped)) {
  2226. return;
  2227. }
  2228. m_orbit_distance = clamped;
  2229. emit orbit_distance_changed();
  2230. update();
  2231. }
  2232. void CampaignMapView::set_pan_u(float pan) {
  2233. const float clamped = qBound(-0.5F, pan, 0.5F);
  2234. if (qFuzzyCompare(m_pan_u, clamped)) {
  2235. return;
  2236. }
  2237. m_pan_u = clamped;
  2238. emit pan_u_changed();
  2239. update();
  2240. }
  2241. void CampaignMapView::set_pan_v(float pan) {
  2242. const float clamped = qBound(-0.5F, pan, 0.5F);
  2243. if (qFuzzyCompare(m_pan_v, clamped)) {
  2244. return;
  2245. }
  2246. m_pan_v = clamped;
  2247. emit pan_v_changed();
  2248. update();
  2249. }
  2250. void CampaignMapView::set_hover_province_id(const QString &province_id) {
  2251. if (m_hover_province_id == province_id) {
  2252. return;
  2253. }
  2254. m_hover_province_id = province_id;
  2255. emit hover_province_id_changed();
  2256. update();
  2257. }
  2258. void CampaignMapView::set_current_mission(int mission) {
  2259. const int clamped = qBound(0, mission, 7);
  2260. if (m_current_mission == clamped) {
  2261. return;
  2262. }
  2263. m_current_mission = clamped;
  2264. emit current_mission_changed();
  2265. update();
  2266. }
  2267. void CampaignMapView::set_terrain_height_scale(float scale) {
  2268. if (qFuzzyCompare(m_terrain_height_scale, scale)) {
  2269. return;
  2270. }
  2271. m_terrain_height_scale = scale;
  2272. emit terrain_height_scale_changed();
  2273. update();
  2274. }
  2275. void CampaignMapView::set_show_province_fills(bool show) {
  2276. if (m_show_province_fills == show) {
  2277. return;
  2278. }
  2279. m_show_province_fills = show;
  2280. emit show_province_fills_changed();
  2281. update();
  2282. }
  2283. auto CampaignMapView::createRenderer() const -> Renderer * {
  2284. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  2285. if ((ctx == nullptr) || !ctx->isValid()) {
  2286. qCritical()
  2287. << "CampaignMapView::createRenderer() - No valid OpenGL context";
  2288. qCritical()
  2289. << "Running in software rendering mode - map view not available";
  2290. return nullptr;
  2291. }
  2292. return new CampaignMapRenderer();
  2293. }