campaign_map_view.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752
  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 = 0.15F;
  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. mesh.height_scale = k_height_scale;
  947. const int grid =
  948. qMax(resolution, qMax(heightmap.width, heightmap.height) / 4);
  949. if (grid > 1) {
  950. const float step = 1.0F / static_cast<float>(grid - 1);
  951. const float sample_dist =
  952. 1.0F / static_cast<float>(qMax(heightmap.width, heightmap.height));
  953. float land_max = 0.0F;
  954. for (float h : heightmap.samples) {
  955. if (h > land_max) {
  956. land_max = h;
  957. }
  958. }
  959. const float land_scale = (land_max > 1e-6F) ? (1.0F / land_max) : 1.0F;
  960. const float edge_margin = 0.03F;
  961. auto sample_height_raw = [&](float u, float v) -> float {
  962. const float cu = qBound(0.0F, u, 1.0F);
  963. const float cv = qBound(0.0F, v, 1.0F);
  964. const float x = cu * static_cast<float>(heightmap.width - 1);
  965. const float y =
  966. (1.0F - cv) * static_cast<float>(heightmap.height - 1);
  967. const int x0 = static_cast<int>(std::floor(x));
  968. const int y0 = static_cast<int>(std::floor(y));
  969. const int x1 = qMin(x0 + 1, heightmap.width - 1);
  970. const int y1 = qMin(y0 + 1, heightmap.height - 1);
  971. const float fx = x - static_cast<float>(x0);
  972. const float fy = y - static_cast<float>(y0);
  973. const float h00 =
  974. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x0)];
  975. const float h10 =
  976. heightmap.samples[static_cast<size_t>(y0 * heightmap.width + x1)];
  977. const float h01 =
  978. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x0)];
  979. const float h11 =
  980. heightmap.samples[static_cast<size_t>(y1 * heightmap.width + x1)];
  981. const float hx0 = h00 + (h10 - h00) * fx;
  982. const float hx1 = h01 + (h11 - h01) * fx;
  983. return hx0 + (hx1 - hx0) * fy;
  984. };
  985. auto sample_height = [&](float u, float v) -> float {
  986. const float h = sample_height_raw(u, v);
  987. float height = (h >= 0.0F) ? (h * land_scale) : 0.0F;
  988. const float edge_dist = qMin(qMin(u, 1.0F - u), qMin(v, 1.0F - v));
  989. if (edge_dist < edge_margin) {
  990. height *= qMax(0.0F, edge_dist / edge_margin);
  991. }
  992. return height;
  993. };
  994. auto sample_normal = [&](float u, float v) -> QVector3D {
  995. const float h_left = sample_height(u - sample_dist, v);
  996. const float h_right = sample_height(u + sample_dist, v);
  997. const float h_down = sample_height(u, v - sample_dist);
  998. const float h_up = sample_height(u, v + sample_dist);
  999. const float dx =
  1000. (h_right - h_left) / (2.0F * sample_dist) * mesh.height_scale;
  1001. const float dz =
  1002. (h_up - h_down) / (2.0F * sample_dist) * mesh.height_scale;
  1003. QVector3D normal(-dx, 1.0F, -dz);
  1004. normal.normalize();
  1005. return normal;
  1006. };
  1007. vertices.reserve(static_cast<size_t>(grid - 1) *
  1008. static_cast<size_t>(grid - 1) * 6 * 8);
  1009. auto add_vertex = [&](float u, float v, float h, const QVector3D &n) {
  1010. vertices.push_back(u);
  1011. vertices.push_back(v);
  1012. vertices.push_back(u);
  1013. vertices.push_back(v);
  1014. vertices.push_back(h);
  1015. vertices.push_back(n.x());
  1016. vertices.push_back(n.y());
  1017. vertices.push_back(n.z());
  1018. };
  1019. for (int y = 0; y < grid - 1; ++y) {
  1020. for (int x = 0; x < grid - 1; ++x) {
  1021. const float u0 = static_cast<float>(x) * step;
  1022. const float v0 = static_cast<float>(y) * step;
  1023. const float u1 = static_cast<float>(x + 1) * step;
  1024. const float v1 = static_cast<float>(y + 1) * step;
  1025. const float h00 = sample_height(u0, v0);
  1026. const float h10 = sample_height(u1, v0);
  1027. const float h01 = sample_height(u0, v1);
  1028. const float h11 = sample_height(u1, v1);
  1029. const QVector3D n00 = sample_normal(u0, v0);
  1030. const QVector3D n10 = sample_normal(u1, v0);
  1031. const QVector3D n01 = sample_normal(u0, v1);
  1032. const QVector3D n11 = sample_normal(u1, v1);
  1033. add_vertex(u0, v0, h00, n00);
  1034. add_vertex(u1, v0, h10, n10);
  1035. add_vertex(u0, v1, h01, n01);
  1036. add_vertex(u1, v0, h10, n10);
  1037. add_vertex(u1, v1, h11, n11);
  1038. add_vertex(u0, v1, h01, n01);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. if (vertices.empty()) {
  1044. mesh.height_scale = k_height_scale;
  1045. vertices = CampaignMapRender::generate_terrain_mesh(resolution, 1.0F);
  1046. }
  1047. if (vertices.empty()) {
  1048. mesh.ready = false;
  1049. return;
  1050. }
  1051. if (mesh.vao == 0) {
  1052. glGenVertexArrays(1, &mesh.vao);
  1053. glGenBuffers(1, &mesh.vbo);
  1054. }
  1055. glBindVertexArray(mesh.vao);
  1056. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1057. glBufferData(GL_ARRAY_BUFFER,
  1058. static_cast<GLsizeiptr>(vertices.size() * sizeof(float)),
  1059. vertices.data(), GL_STATIC_DRAW);
  1060. const int stride = 8 * sizeof(float);
  1061. glEnableVertexAttribArray(0);
  1062. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1063. reinterpret_cast<void *>(0));
  1064. glEnableVertexAttribArray(1);
  1065. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1066. reinterpret_cast<void *>(2 * sizeof(float)));
  1067. glEnableVertexAttribArray(2);
  1068. glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, stride,
  1069. reinterpret_cast<void *>(4 * sizeof(float)));
  1070. glEnableVertexAttribArray(3);
  1071. glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride,
  1072. reinterpret_cast<void *>(5 * sizeof(float)));
  1073. glBindVertexArray(0);
  1074. mesh.vertex_count = static_cast<int>(vertices.size() / 8);
  1075. mesh.ready = true;
  1076. }
  1077. void init_hillshade_layer(HillshadeLayer &layer, int width, int height) {
  1078. CampaignMapRender::HillshadeConfig config;
  1079. config.light_direction = layer.light_direction;
  1080. config.ambient = layer.ambient;
  1081. config.intensity = layer.intensity;
  1082. std::vector<unsigned char> pixels =
  1083. CampaignMapRender::generate_hillshade_texture(width, height, config);
  1084. if (pixels.empty()) {
  1085. layer.ready = false;
  1086. return;
  1087. }
  1088. if (layer.texture_id == 0) {
  1089. glGenTextures(1, &layer.texture_id);
  1090. }
  1091. glBindTexture(GL_TEXTURE_2D, layer.texture_id);
  1092. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
  1093. GL_UNSIGNED_BYTE, pixels.data());
  1094. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1095. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1096. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  1097. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  1098. glBindTexture(GL_TEXTURE_2D, 0);
  1099. layer.width = width;
  1100. layer.height = height;
  1101. layer.ready = true;
  1102. }
  1103. auto load_heightmap_data(const QString &image_path,
  1104. const QString &meta_path) -> HeightmapData {
  1105. HeightmapData data;
  1106. const QString resolved_image =
  1107. Utils::Resources::resolveResourcePath(image_path);
  1108. QImage image(resolved_image);
  1109. if (image.isNull()) {
  1110. qWarning() << "CampaignMapRenderer: Failed to load heightmap"
  1111. << resolved_image;
  1112. return data;
  1113. }
  1114. if (image.format() != QImage::Format_Grayscale16) {
  1115. image = image.convertToFormat(QImage::Format_Grayscale16);
  1116. }
  1117. if (image.isNull()) {
  1118. qWarning() << "CampaignMapRenderer: Heightmap conversion failed"
  1119. << resolved_image;
  1120. return data;
  1121. }
  1122. float min_m = -6000.0F;
  1123. float max_m = 4000.0F;
  1124. const QString resolved_meta =
  1125. Utils::Resources::resolveResourcePath(meta_path);
  1126. QFile meta_file(resolved_meta);
  1127. if (meta_file.open(QIODevice::ReadOnly)) {
  1128. const QJsonDocument doc = QJsonDocument::fromJson(meta_file.readAll());
  1129. if (doc.isObject()) {
  1130. const QJsonObject obj = doc.object();
  1131. if (obj.contains("min_m")) {
  1132. min_m = static_cast<float>(obj.value("min_m").toDouble());
  1133. }
  1134. if (obj.contains("max_m")) {
  1135. max_m = static_cast<float>(obj.value("max_m").toDouble());
  1136. }
  1137. }
  1138. }
  1139. if (!(min_m < max_m)) {
  1140. qWarning() << "CampaignMapRenderer: Heightmap metadata invalid"
  1141. << resolved_meta;
  1142. return data;
  1143. }
  1144. const int width = image.width();
  1145. const int height = image.height();
  1146. if (width <= 1 || height <= 1) {
  1147. qWarning() << "CampaignMapRenderer: Heightmap dimensions invalid" << width
  1148. << height;
  1149. return data;
  1150. }
  1151. const float range = max_m - min_m;
  1152. const float max_abs = qMax(std::abs(min_m), std::abs(max_m));
  1153. if (max_abs <= 0.0F) {
  1154. return data;
  1155. }
  1156. data.samples.resize(static_cast<size_t>(width * height));
  1157. for (int y = 0; y < height; ++y) {
  1158. const auto *row =
  1159. reinterpret_cast<const quint16 *>(image.constScanLine(y));
  1160. for (int x = 0; x < width; ++x) {
  1161. const float norm = static_cast<float>(row[x]) / 65535.0F;
  1162. const float height_m = min_m + norm * range;
  1163. data.samples[static_cast<size_t>(y * width + x)] = height_m / max_abs;
  1164. }
  1165. }
  1166. data.width = width;
  1167. data.height = height;
  1168. data.min_m = min_m;
  1169. data.max_m = max_m;
  1170. data.ready = true;
  1171. return data;
  1172. }
  1173. void init_label_layer(LabelLayer &layer, const QString &resource_path) {
  1174. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1175. QFile file(path);
  1176. if (!file.open(QIODevice::ReadOnly)) {
  1177. qWarning() << "CampaignMapRenderer: Failed to open labels source" << path;
  1178. return;
  1179. }
  1180. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1181. if (!doc.isObject()) {
  1182. qWarning() << "CampaignMapRenderer: Labels JSON invalid" << path;
  1183. return;
  1184. }
  1185. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1186. for (const auto &prov_val : provinces) {
  1187. const QJsonObject prov = prov_val.toObject();
  1188. const QString name = prov.value("name").toString();
  1189. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1190. if (name.isEmpty() || label_uv.size() < 2) {
  1191. continue;
  1192. }
  1193. ProvinceLabel label;
  1194. label.text = name;
  1195. label.position = QVector2D(static_cast<float>(label_uv.at(0).toDouble()),
  1196. static_cast<float>(label_uv.at(1).toDouble()));
  1197. const QString id = prov.value("id").toString().toLower();
  1198. if (id.contains("core") || id.contains("capital")) {
  1199. label.importance = 3;
  1200. } else if (id.contains("major") ||
  1201. prov.value("cities").toArray().size() > 2) {
  1202. label.importance = 2;
  1203. } else {
  1204. label.importance = 1;
  1205. }
  1206. label.is_sea = id.contains("sea") || id.contains("mare") ||
  1207. id.contains("mediterranean");
  1208. layer.labels.push_back(label);
  1209. }
  1210. build_label_geometry(layer);
  1211. }
  1212. void build_label_geometry(LabelLayer &layer) {
  1213. std::vector<float> verts;
  1214. for (const auto &label : layer.labels) {
  1215. CampaignMapRender::LabelStyle style;
  1216. if (label.is_sea) {
  1217. style = CampaignMapRender::LabelStyles::sea_label();
  1218. } else if (label.importance >= 3) {
  1219. style = CampaignMapRender::LabelStyles::region_label();
  1220. } else if (label.importance >= 2) {
  1221. style = CampaignMapRender::LabelStyles::province_label();
  1222. } else {
  1223. style = CampaignMapRender::LabelStyles::city_label();
  1224. }
  1225. std::vector<float> label_verts = CampaignMapRender::generate_label_quads(
  1226. label.position, label.text.toStdString(), style);
  1227. verts.insert(verts.end(), label_verts.begin(), label_verts.end());
  1228. }
  1229. if (verts.empty()) {
  1230. layer.ready = false;
  1231. return;
  1232. }
  1233. if (layer.vao == 0) {
  1234. glGenVertexArrays(1, &layer.vao);
  1235. glGenBuffers(1, &layer.vbo);
  1236. }
  1237. glBindVertexArray(layer.vao);
  1238. glBindBuffer(GL_ARRAY_BUFFER, layer.vbo);
  1239. glBufferData(GL_ARRAY_BUFFER,
  1240. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1241. verts.data(), GL_STATIC_DRAW);
  1242. const int stride = 6 * sizeof(float);
  1243. glEnableVertexAttribArray(0);
  1244. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride,
  1245. reinterpret_cast<void *>(0));
  1246. glEnableVertexAttribArray(1);
  1247. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
  1248. reinterpret_cast<void *>(2 * sizeof(float)));
  1249. glEnableVertexAttribArray(2);
  1250. glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride,
  1251. reinterpret_cast<void *>(4 * sizeof(float)));
  1252. glBindVertexArray(0);
  1253. layer.total_vertices = static_cast<int>(verts.size() / 6);
  1254. layer.ready = true;
  1255. }
  1256. void draw_label_layer(const LabelLayer &layer, const QMatrix4x4 &mvp,
  1257. float z_offset) {
  1258. if (!layer.ready || layer.vao == 0 || layer.total_vertices <= 0) {
  1259. return;
  1260. }
  1261. if (layer.font_texture == 0) {
  1262. return;
  1263. }
  1264. m_line_program.bind();
  1265. m_line_program.setUniformValue("u_mvp", mvp);
  1266. m_line_program.setUniformValue("u_z", z_offset);
  1267. m_line_program.setUniformValue("u_color",
  1268. QVector4D(0.25F, 0.20F, 0.15F, 0.85F));
  1269. glBindVertexArray(layer.vao);
  1270. glDrawArrays(GL_TRIANGLES, 0, layer.total_vertices);
  1271. glBindVertexArray(0);
  1272. m_line_program.release();
  1273. }
  1274. auto load_texture(const QString &resource_path) -> QOpenGLTexture * {
  1275. const QString path = Utils::Resources::resolveResourcePath(resource_path);
  1276. QImage image(path);
  1277. if (image.isNull()) {
  1278. qWarning() << "CampaignMapRenderer: Failed to load texture" << path;
  1279. return nullptr;
  1280. }
  1281. QImage rgba = image.convertToFormat(QImage::Format_RGBA8888);
  1282. auto *texture = new QOpenGLTexture(rgba);
  1283. texture->setWrapMode(QOpenGLTexture::ClampToEdge);
  1284. texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
  1285. return texture;
  1286. }
  1287. void compute_mvp(QMatrix4x4 &out_mvp) const {
  1288. out_mvp = build_mvp_matrix(
  1289. static_cast<float>(m_size.width()), static_cast<float>(m_size.height()),
  1290. m_orbit_yaw, m_orbit_pitch, m_orbit_distance, m_pan_u, m_pan_v);
  1291. }
  1292. void draw_textured_layer(QOpenGLTexture *texture, GLuint vao,
  1293. int vertex_count, const QMatrix4x4 &mvp, float alpha,
  1294. float z_offset) {
  1295. if (texture == nullptr || vao == 0 || vertex_count <= 0) {
  1296. return;
  1297. }
  1298. m_texture_program.bind();
  1299. m_texture_program.setUniformValue("u_mvp", mvp);
  1300. m_texture_program.setUniformValue("u_z", z_offset);
  1301. m_texture_program.setUniformValue("u_alpha", alpha);
  1302. m_texture_program.setUniformValue("u_tex", 0);
  1303. glActiveTexture(GL_TEXTURE0);
  1304. texture->bind();
  1305. glBindVertexArray(vao);
  1306. glDrawArrays(GL_TRIANGLES, 0, vertex_count);
  1307. glBindVertexArray(0);
  1308. texture->release();
  1309. m_texture_program.release();
  1310. }
  1311. void draw_terrain_layer(const TerrainMesh &mesh, const QMatrix4x4 &mvp) {
  1312. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0 ||
  1313. m_base_texture == nullptr || !m_terrain_program.isLinked()) {
  1314. return;
  1315. }
  1316. m_terrain_program.bind();
  1317. m_terrain_program.setUniformValue("u_mvp", mvp);
  1318. m_terrain_program.setUniformValue(
  1319. "u_height_scale", mesh.height_scale * m_terrain_height_scale);
  1320. m_terrain_program.setUniformValue("u_z_base", mesh.z_base);
  1321. m_terrain_program.setUniformValue("u_light_direction",
  1322. QVector3D(0.35F, 0.85F, 0.40F));
  1323. m_terrain_program.setUniformValue("u_ambient_strength", 0.45F);
  1324. m_terrain_program.setUniformValue("u_hillshade_strength", 0.35F);
  1325. m_terrain_program.setUniformValue("u_ao_strength", 0.25F);
  1326. m_terrain_program.setUniformValue("u_use_hillshade", true);
  1327. m_terrain_program.setUniformValue("u_use_parchment", false);
  1328. m_terrain_program.setUniformValue("u_use_lighting", true);
  1329. m_terrain_program.setUniformValue("u_water_deep_color",
  1330. QVector3D(0.10F, 0.22F, 0.30F));
  1331. m_terrain_program.setUniformValue("u_water_shallow_color",
  1332. QVector3D(0.26F, 0.42F, 0.52F));
  1333. m_terrain_program.setUniformValue("u_lowland_tint",
  1334. QVector3D(0.96F, 0.92F, 0.86F));
  1335. m_terrain_program.setUniformValue("u_highland_tint",
  1336. QVector3D(0.82F, 0.74F, 0.64F));
  1337. m_terrain_program.setUniformValue("u_mountain_tint",
  1338. QVector3D(0.70F, 0.62F, 0.55F));
  1339. m_terrain_program.setUniformValue("u_elevation_scale", 1.2F);
  1340. m_terrain_program.setUniformValue("u_base_texture", 0);
  1341. glActiveTexture(GL_TEXTURE0);
  1342. m_base_texture->bind();
  1343. glBindVertexArray(mesh.vao);
  1344. glDrawArrays(GL_TRIANGLES, 0, mesh.vertex_count);
  1345. glBindVertexArray(0);
  1346. m_base_texture->release();
  1347. m_terrain_program.release();
  1348. }
  1349. void draw_line_layer(const LineLayer &layer, const QMatrix4x4 &mvp,
  1350. float z_offset) {
  1351. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1352. return;
  1353. }
  1354. m_line_program.bind();
  1355. m_line_program.setUniformValue("u_mvp", mvp);
  1356. if (layer.double_stroke) {
  1357. glLineWidth(layer.width * layer.outer_width_ratio);
  1358. m_line_program.setUniformValue("u_z", z_offset);
  1359. m_line_program.setUniformValue("u_color", layer.outer_color);
  1360. glBindVertexArray(layer.vao);
  1361. for (const auto &span : layer.spans) {
  1362. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1363. }
  1364. glLineWidth(layer.width * layer.inner_width_ratio);
  1365. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1366. m_line_program.setUniformValue("u_color", layer.inner_color);
  1367. for (const auto &span : layer.spans) {
  1368. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1369. }
  1370. glBindVertexArray(0);
  1371. } else {
  1372. glLineWidth(layer.width);
  1373. m_line_program.setUniformValue("u_z", z_offset);
  1374. m_line_program.setUniformValue("u_color", layer.color);
  1375. glBindVertexArray(layer.vao);
  1376. for (const auto &span : layer.spans) {
  1377. glDrawArrays(GL_LINE_STRIP, span.start, span.count);
  1378. }
  1379. glBindVertexArray(0);
  1380. }
  1381. m_line_program.release();
  1382. }
  1383. static auto safe_normalized(const QVector2D &v) -> QVector2D {
  1384. const float len = v.length();
  1385. if (len < 1e-5F) {
  1386. return QVector2D(0.0F, 0.0F);
  1387. }
  1388. return v / len;
  1389. }
  1390. static auto perp(const QVector2D &v) -> QVector2D {
  1391. return QVector2D(-v.y(), v.x());
  1392. }
  1393. void build_path_strip(const std::vector<QVector2D> &input, float half_width,
  1394. std::vector<QVector2D> &out) const {
  1395. out.clear();
  1396. if (input.size() < 2 || half_width <= 0.0F) {
  1397. return;
  1398. }
  1399. std::vector<QVector2D> points;
  1400. points.reserve(input.size());
  1401. for (const auto &pt : input) {
  1402. if (points.empty()) {
  1403. points.push_back(pt);
  1404. continue;
  1405. }
  1406. const QVector2D delta = pt - points.back();
  1407. if (QVector2D::dotProduct(delta, delta) > 1e-10F) {
  1408. points.push_back(pt);
  1409. }
  1410. }
  1411. if (points.size() < 2) {
  1412. return;
  1413. }
  1414. out.reserve(points.size() * 2);
  1415. for (size_t i = 0; i < points.size(); ++i) {
  1416. QVector2D offset;
  1417. if (i == 0) {
  1418. const QVector2D dir = safe_normalized(points[1] - points[0]);
  1419. offset = perp(dir) * half_width;
  1420. } else if (i + 1 == points.size()) {
  1421. const QVector2D dir = safe_normalized(points[i] - points[i - 1]);
  1422. offset = perp(dir) * half_width;
  1423. } else {
  1424. QVector2D dir0 = safe_normalized(points[i] - points[i - 1]);
  1425. QVector2D dir1 = safe_normalized(points[i + 1] - points[i]);
  1426. if (dir0.isNull()) {
  1427. dir0 = dir1;
  1428. }
  1429. if (dir1.isNull()) {
  1430. dir1 = dir0;
  1431. }
  1432. const QVector2D n0 = perp(dir0);
  1433. const QVector2D n1 = perp(dir1);
  1434. QVector2D miter = safe_normalized(n0 + n1);
  1435. if (miter.isNull()) {
  1436. miter = n1;
  1437. }
  1438. float denom = QVector2D::dotProduct(miter, n1);
  1439. if (std::abs(denom) < 0.2F) {
  1440. denom = (denom >= 0.0F) ? 0.2F : -0.2F;
  1441. }
  1442. float miter_len = half_width / denom;
  1443. const float max_miter = half_width * 3.0F;
  1444. if (std::abs(miter_len) > max_miter) {
  1445. miter_len = (miter_len < 0.0F) ? -max_miter : max_miter;
  1446. }
  1447. offset = miter * miter_len;
  1448. }
  1449. out.push_back(points[i] + offset);
  1450. out.push_back(points[i] - offset);
  1451. }
  1452. }
  1453. void update_path_mesh(StrokeMesh &mesh, const std::vector<QVector2D> &points,
  1454. float width) {
  1455. if (points.size() < 2) {
  1456. mesh.ready = false;
  1457. mesh.vertex_count = 0;
  1458. return;
  1459. }
  1460. if (mesh.ready && qFuzzyCompare(mesh.width, width)) {
  1461. return;
  1462. }
  1463. CampaignMapRender::StrokeMeshConfig config;
  1464. config.width = width;
  1465. config.start_cap = CampaignMapRender::CapStyle::Round;
  1466. config.end_cap = CampaignMapRender::CapStyle::Round;
  1467. config.join_style = CampaignMapRender::JoinStyle::Miter;
  1468. config.cap_segments = 6;
  1469. config.miter_params.max_miter_ratio = 3.0F;
  1470. std::vector<QVector2D> strip =
  1471. CampaignMapRender::build_stroke_mesh(points, config);
  1472. if (strip.size() < 4) {
  1473. mesh.ready = false;
  1474. mesh.vertex_count = 0;
  1475. return;
  1476. }
  1477. std::vector<float> verts;
  1478. verts.reserve(strip.size() * 2);
  1479. for (const auto &v : strip) {
  1480. verts.push_back(v.x());
  1481. verts.push_back(v.y());
  1482. }
  1483. if (mesh.vao == 0) {
  1484. glGenVertexArrays(1, &mesh.vao);
  1485. glGenBuffers(1, &mesh.vbo);
  1486. }
  1487. glBindVertexArray(mesh.vao);
  1488. glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
  1489. glBufferData(GL_ARRAY_BUFFER,
  1490. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1491. verts.data(), GL_DYNAMIC_DRAW);
  1492. glEnableVertexAttribArray(0);
  1493. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float),
  1494. reinterpret_cast<void *>(0));
  1495. glBindVertexArray(0);
  1496. mesh.vertex_count = static_cast<int>(strip.size());
  1497. mesh.width = width;
  1498. mesh.ready = true;
  1499. }
  1500. auto uv_width_for_pixels(float px) const -> float {
  1501. const float viewport_h = qMax(1.0F, static_cast<float>(m_size.height()));
  1502. const float fov_rad = qDegreesToRadians(45.0F * 0.5F);
  1503. const float view_h = 2.0F * m_orbit_distance * std::tan(fov_rad);
  1504. const float uv_width = px * (view_h / viewport_h);
  1505. return qMax(0.0005F, uv_width);
  1506. }
  1507. void draw_path_mesh(const StrokeMesh &mesh) {
  1508. if (!mesh.ready || mesh.vao == 0 || mesh.vertex_count <= 0) {
  1509. return;
  1510. }
  1511. glBindVertexArray(mesh.vao);
  1512. glDrawArrays(GL_TRIANGLE_STRIP, 0, mesh.vertex_count);
  1513. glBindVertexArray(0);
  1514. }
  1515. void draw_progressive_path_layers(PathLayer &layer, const QMatrix4x4 &mvp,
  1516. float z_offset) {
  1517. if (!layer.ready || layer.lines.empty()) {
  1518. return;
  1519. }
  1520. const int max_mission =
  1521. qBound(0, m_current_mission, static_cast<int>(layer.lines.size()) - 1);
  1522. m_line_program.bind();
  1523. m_line_program.setUniformValue("u_mvp", mvp);
  1524. for (int i = 0; i <= max_mission; ++i) {
  1525. if (i >= static_cast<int>(layer.lines.size())) {
  1526. break;
  1527. }
  1528. auto &line = layer.lines[static_cast<size_t>(i)];
  1529. const int age = max_mission - i;
  1530. auto passes =
  1531. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1532. age);
  1533. if (!passes.empty()) {
  1534. const auto &border_pass = passes[0];
  1535. float border_width_px = 6.0F * border_pass.width_multiplier;
  1536. if (i != max_mission) {
  1537. border_width_px *= 0.85F;
  1538. }
  1539. m_line_program.setUniformValue("u_z", z_offset + border_pass.z_offset);
  1540. update_path_mesh(line.border, line.points,
  1541. uv_width_for_pixels(border_width_px));
  1542. m_line_program.setUniformValue("u_color", border_pass.color);
  1543. draw_path_mesh(line.border);
  1544. }
  1545. }
  1546. for (int i = 0; i <= max_mission; ++i) {
  1547. if (i >= static_cast<int>(layer.lines.size())) {
  1548. break;
  1549. }
  1550. auto &line = layer.lines[static_cast<size_t>(i)];
  1551. const int age = max_mission - i;
  1552. auto passes =
  1553. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1554. age);
  1555. if (passes.size() > 2) {
  1556. const auto &highlight_pass = passes[2];
  1557. float highlight_width_px = 4.0F * highlight_pass.width_multiplier;
  1558. if (i != max_mission) {
  1559. highlight_width_px *= 0.8F;
  1560. }
  1561. m_line_program.setUniformValue("u_z",
  1562. z_offset + highlight_pass.z_offset);
  1563. update_path_mesh(line.highlight, line.points,
  1564. uv_width_for_pixels(highlight_width_px));
  1565. m_line_program.setUniformValue("u_color", highlight_pass.color);
  1566. draw_path_mesh(line.highlight);
  1567. }
  1568. }
  1569. for (int i = 0; i <= max_mission; ++i) {
  1570. if (i >= static_cast<int>(layer.lines.size())) {
  1571. break;
  1572. }
  1573. auto &line = layer.lines[static_cast<size_t>(i)];
  1574. const int age = max_mission - i;
  1575. auto passes =
  1576. CampaignMapRender::CartographicStyles::get_inked_route_passes(1.0F,
  1577. age);
  1578. if (passes.size() > 3) {
  1579. const auto &core_pass = passes[3];
  1580. float core_width_px = 3.0F * core_pass.width_multiplier;
  1581. if (i != max_mission) {
  1582. core_width_px *= 0.75F;
  1583. }
  1584. m_line_program.setUniformValue("u_z", z_offset + core_pass.z_offset);
  1585. update_path_mesh(line.core, line.points,
  1586. uv_width_for_pixels(core_width_px));
  1587. m_line_program.setUniformValue("u_color", core_pass.color);
  1588. draw_path_mesh(line.core);
  1589. }
  1590. }
  1591. m_line_program.release();
  1592. }
  1593. void update_mission_badge_position(MissionBadge &badge,
  1594. const PathLayer &path_layer,
  1595. int mission_index) {
  1596. if (!path_layer.ready || path_layer.lines.empty()) {
  1597. badge.ready = false;
  1598. return;
  1599. }
  1600. const int clamped_mission =
  1601. qBound(0, mission_index, static_cast<int>(path_layer.lines.size()) - 1);
  1602. const auto &line = path_layer.lines[static_cast<size_t>(clamped_mission)];
  1603. if (line.points.empty()) {
  1604. badge.ready = false;
  1605. return;
  1606. }
  1607. badge.position = line.points.back();
  1608. badge.ready = true;
  1609. }
  1610. void build_badge_geometry(MissionBadge &badge) {
  1611. if (!badge.ready) {
  1612. return;
  1613. }
  1614. std::vector<QVector2D> outline = CampaignMapRender::generate_shield_badge(
  1615. QVector2D(0.0F, 0.0F), 1.0F, 16);
  1616. if (outline.size() < 3) {
  1617. badge.ready = false;
  1618. return;
  1619. }
  1620. std::vector<float> verts;
  1621. verts.reserve((outline.size() + 1) * 4);
  1622. verts.push_back(badge.position.x());
  1623. verts.push_back(badge.position.y());
  1624. verts.push_back(0.0F);
  1625. verts.push_back(0.0F);
  1626. for (const auto &pt : outline) {
  1627. verts.push_back(badge.position.x() + pt.x() * badge.size);
  1628. verts.push_back(badge.position.y() + pt.y() * badge.size);
  1629. verts.push_back(pt.x());
  1630. verts.push_back(pt.y());
  1631. }
  1632. if (badge.vao == 0) {
  1633. glGenVertexArrays(1, &badge.vao);
  1634. glGenBuffers(1, &badge.vbo);
  1635. }
  1636. glBindVertexArray(badge.vao);
  1637. glBindBuffer(GL_ARRAY_BUFFER, badge.vbo);
  1638. glBufferData(GL_ARRAY_BUFFER,
  1639. static_cast<GLsizeiptr>(verts.size() * sizeof(float)),
  1640. verts.data(), GL_DYNAMIC_DRAW);
  1641. glEnableVertexAttribArray(0);
  1642. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1643. reinterpret_cast<void *>(0));
  1644. glEnableVertexAttribArray(1);
  1645. glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
  1646. reinterpret_cast<void *>(2 * sizeof(float)));
  1647. glBindVertexArray(0);
  1648. badge.vertex_count = static_cast<int>(outline.size() + 1);
  1649. }
  1650. void draw_mission_badge(MissionBadge &badge, const QMatrix4x4 &mvp,
  1651. float z_offset) {
  1652. if (!badge.ready) {
  1653. return;
  1654. }
  1655. update_mission_badge_position(badge, m_path_layer, m_current_mission);
  1656. build_badge_geometry(badge);
  1657. if (badge.vao == 0 || badge.vertex_count < 3) {
  1658. return;
  1659. }
  1660. m_line_program.bind();
  1661. m_line_program.setUniformValue("u_mvp", mvp);
  1662. if (badge.show_shadow) {
  1663. m_line_program.setUniformValue("u_z", z_offset);
  1664. m_line_program.setUniformValue("u_color", badge.shadow_color);
  1665. glBindVertexArray(badge.vao);
  1666. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1667. glBindVertexArray(0);
  1668. }
  1669. m_line_program.setUniformValue("u_z", z_offset + 0.001F);
  1670. m_line_program.setUniformValue("u_color", badge.border_color);
  1671. glBindVertexArray(badge.vao);
  1672. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1673. glBindVertexArray(0);
  1674. m_line_program.setUniformValue("u_z", z_offset + 0.002F);
  1675. m_line_program.setUniformValue("u_color", badge.primary_color);
  1676. glBindVertexArray(badge.vao);
  1677. glDrawArrays(GL_TRIANGLE_FAN, 0, badge.vertex_count);
  1678. glBindVertexArray(0);
  1679. m_line_program.release();
  1680. }
  1681. void apply_province_overrides(
  1682. const QHash<QString, CampaignMapView::ProvinceVisual> &overrides) {
  1683. if (!m_province_layer.ready || m_province_layer.spans.empty()) {
  1684. return;
  1685. }
  1686. for (auto &span : m_province_layer.spans) {
  1687. const auto it = overrides.find(span.id);
  1688. if (it != overrides.end() && it->has_color) {
  1689. span.color = it->color;
  1690. } else {
  1691. span.color = span.base_color;
  1692. }
  1693. }
  1694. }
  1695. void draw_province_layer(const ProvinceLayer &layer, const QMatrix4x4 &mvp,
  1696. float z_offset) {
  1697. if (!layer.ready || layer.vao == 0 || layer.spans.empty()) {
  1698. return;
  1699. }
  1700. m_line_program.bind();
  1701. m_line_program.setUniformValue("u_mvp", mvp);
  1702. m_line_program.setUniformValue("u_z", z_offset);
  1703. glBindVertexArray(layer.vao);
  1704. for (const auto &span : layer.spans) {
  1705. if (span.color.w() <= 0.0F) {
  1706. continue;
  1707. }
  1708. QVector4D color = span.color;
  1709. const float parchment_tint = 0.92F;
  1710. color.setX(color.x() * parchment_tint);
  1711. color.setY(color.y() * parchment_tint);
  1712. color.setZ(color.z() * parchment_tint * 0.98F);
  1713. if (m_terrain_mesh.ready && m_terrain_height_scale > 0.01F) {
  1714. float fade = 1.0F / (1.0F + 3.0F * m_terrain_height_scale);
  1715. color.setW(color.w() * fade);
  1716. }
  1717. if (!m_hover_province_id.isEmpty() && span.id == m_hover_province_id) {
  1718. qint64 elapsed =
  1719. QDateTime::currentMSecsSinceEpoch() - m_hover_start_time;
  1720. float pulse_cycle = 1200.0F;
  1721. float pulse =
  1722. 0.5F + 0.5F * std::sin(elapsed * 2.0F * M_PI / pulse_cycle);
  1723. float brightness_boost = 0.3F + 0.15F * pulse;
  1724. color = QVector4D(qMin(1.0F, color.x() + brightness_boost),
  1725. qMin(1.0F, color.y() + brightness_boost),
  1726. qMin(1.0F, color.z() + brightness_boost),
  1727. qMin(1.0F, color.w() + 0.2F));
  1728. }
  1729. m_line_program.setUniformValue("u_color", color);
  1730. glDrawArrays(GL_TRIANGLES, span.start, span.count);
  1731. }
  1732. glBindVertexArray(0);
  1733. m_line_program.release();
  1734. }
  1735. void cleanup() {
  1736. if (QOpenGLContext::currentContext() == nullptr) {
  1737. return;
  1738. }
  1739. if (m_quad_vbo != 0) {
  1740. glDeleteBuffers(1, &m_quad_vbo);
  1741. m_quad_vbo = 0;
  1742. }
  1743. if (m_quad_vao != 0) {
  1744. glDeleteVertexArrays(1, &m_quad_vao);
  1745. m_quad_vao = 0;
  1746. }
  1747. if (m_land_vbo != 0) {
  1748. glDeleteBuffers(1, &m_land_vbo);
  1749. m_land_vbo = 0;
  1750. }
  1751. if (m_land_vao != 0) {
  1752. glDeleteVertexArrays(1, &m_land_vao);
  1753. m_land_vao = 0;
  1754. }
  1755. if (m_coast_layer.vbo != 0) {
  1756. glDeleteBuffers(1, &m_coast_layer.vbo);
  1757. m_coast_layer.vbo = 0;
  1758. }
  1759. if (m_coast_layer.vao != 0) {
  1760. glDeleteVertexArrays(1, &m_coast_layer.vao);
  1761. m_coast_layer.vao = 0;
  1762. }
  1763. if (m_river_layer.vbo != 0) {
  1764. glDeleteBuffers(1, &m_river_layer.vbo);
  1765. m_river_layer.vbo = 0;
  1766. }
  1767. if (m_river_layer.vao != 0) {
  1768. glDeleteVertexArrays(1, &m_river_layer.vao);
  1769. m_river_layer.vao = 0;
  1770. }
  1771. for (auto &line : m_path_layer.lines) {
  1772. if (line.border.vbo != 0) {
  1773. glDeleteBuffers(1, &line.border.vbo);
  1774. line.border.vbo = 0;
  1775. }
  1776. if (line.border.vao != 0) {
  1777. glDeleteVertexArrays(1, &line.border.vao);
  1778. line.border.vao = 0;
  1779. }
  1780. if (line.highlight.vbo != 0) {
  1781. glDeleteBuffers(1, &line.highlight.vbo);
  1782. line.highlight.vbo = 0;
  1783. }
  1784. if (line.highlight.vao != 0) {
  1785. glDeleteVertexArrays(1, &line.highlight.vao);
  1786. line.highlight.vao = 0;
  1787. }
  1788. if (line.core.vbo != 0) {
  1789. glDeleteBuffers(1, &line.core.vbo);
  1790. line.core.vbo = 0;
  1791. }
  1792. if (line.core.vao != 0) {
  1793. glDeleteVertexArrays(1, &line.core.vao);
  1794. line.core.vao = 0;
  1795. }
  1796. }
  1797. m_path_layer.lines.clear();
  1798. if (m_province_border_layer.vbo != 0) {
  1799. glDeleteBuffers(1, &m_province_border_layer.vbo);
  1800. m_province_border_layer.vbo = 0;
  1801. }
  1802. if (m_province_border_layer.vao != 0) {
  1803. glDeleteVertexArrays(1, &m_province_border_layer.vao);
  1804. m_province_border_layer.vao = 0;
  1805. }
  1806. if (m_province_layer.vbo != 0) {
  1807. glDeleteBuffers(1, &m_province_layer.vbo);
  1808. m_province_layer.vbo = 0;
  1809. }
  1810. if (m_province_layer.vao != 0) {
  1811. glDeleteVertexArrays(1, &m_province_layer.vao);
  1812. m_province_layer.vao = 0;
  1813. }
  1814. if (m_mission_badge.vbo != 0) {
  1815. glDeleteBuffers(1, &m_mission_badge.vbo);
  1816. m_mission_badge.vbo = 0;
  1817. }
  1818. if (m_mission_badge.vao != 0) {
  1819. glDeleteVertexArrays(1, &m_mission_badge.vao);
  1820. m_mission_badge.vao = 0;
  1821. }
  1822. m_mission_badge.ready = false;
  1823. if (m_symbol_layer.vbo != 0) {
  1824. glDeleteBuffers(1, &m_symbol_layer.vbo);
  1825. m_symbol_layer.vbo = 0;
  1826. }
  1827. if (m_symbol_layer.vao != 0) {
  1828. glDeleteVertexArrays(1, &m_symbol_layer.vao);
  1829. m_symbol_layer.vao = 0;
  1830. }
  1831. m_symbol_layer.symbols.clear();
  1832. m_symbol_layer.ready = false;
  1833. if (m_terrain_mesh.vbo != 0) {
  1834. glDeleteBuffers(1, &m_terrain_mesh.vbo);
  1835. m_terrain_mesh.vbo = 0;
  1836. }
  1837. if (m_terrain_mesh.vao != 0) {
  1838. glDeleteVertexArrays(1, &m_terrain_mesh.vao);
  1839. m_terrain_mesh.vao = 0;
  1840. }
  1841. m_terrain_mesh.ready = false;
  1842. if (m_hillshade.texture_id != 0) {
  1843. glDeleteTextures(1, &m_hillshade.texture_id);
  1844. m_hillshade.texture_id = 0;
  1845. }
  1846. m_hillshade.ready = false;
  1847. if (m_label_layer.vbo != 0) {
  1848. glDeleteBuffers(1, &m_label_layer.vbo);
  1849. m_label_layer.vbo = 0;
  1850. }
  1851. if (m_label_layer.vao != 0) {
  1852. glDeleteVertexArrays(1, &m_label_layer.vao);
  1853. m_label_layer.vao = 0;
  1854. }
  1855. if (m_label_layer.font_texture != 0) {
  1856. glDeleteTextures(1, &m_label_layer.font_texture);
  1857. m_label_layer.font_texture = 0;
  1858. }
  1859. m_label_layer.labels.clear();
  1860. m_label_layer.ready = false;
  1861. m_base_texture = nullptr;
  1862. m_water_texture = nullptr;
  1863. }
  1864. };
  1865. } // namespace
  1866. CampaignMapView::CampaignMapView() { setMirrorVertically(true); }
  1867. void CampaignMapView::load_provinces_for_hit_test() {
  1868. if (m_provinces_loaded) {
  1869. return;
  1870. }
  1871. m_provinces_loaded = true;
  1872. m_provinces.clear();
  1873. const QString path = Utils::Resources::resolveResourcePath(
  1874. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1875. QFile file(path);
  1876. if (!file.open(QIODevice::ReadOnly)) {
  1877. return;
  1878. }
  1879. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1880. if (!doc.isObject()) {
  1881. return;
  1882. }
  1883. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1884. for (const auto &prov_val : provinces) {
  1885. const QJsonObject prov = prov_val.toObject();
  1886. const QJsonArray tri = prov.value("triangles").toArray();
  1887. if (tri.isEmpty()) {
  1888. continue;
  1889. }
  1890. ProvinceHit province;
  1891. province.id = prov.value("id").toString();
  1892. province.name = prov.value("name").toString();
  1893. province.owner = prov.value("owner").toString();
  1894. province.triangles.reserve(static_cast<size_t>(tri.size()));
  1895. for (const auto &pt_val : tri) {
  1896. const QJsonArray pt = pt_val.toArray();
  1897. if (pt.size() < 2) {
  1898. continue;
  1899. }
  1900. province.triangles.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  1901. static_cast<float>(pt.at(1).toDouble()));
  1902. }
  1903. if (province.triangles.size() >= 3) {
  1904. m_provinces.push_back(std::move(province));
  1905. }
  1906. }
  1907. if (!m_province_overrides.isEmpty()) {
  1908. for (auto &province : m_provinces) {
  1909. const auto it = m_province_overrides.find(province.id);
  1910. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1911. province.owner = it->owner;
  1912. }
  1913. }
  1914. }
  1915. }
  1916. void CampaignMapView::load_province_labels() {
  1917. if (m_province_labels_loaded) {
  1918. return;
  1919. }
  1920. m_province_labels_loaded = true;
  1921. m_province_labels.clear();
  1922. const QString path = Utils::Resources::resolveResourcePath(
  1923. QStringLiteral(":/assets/campaign_map/provinces.json"));
  1924. QFile file(path);
  1925. if (!file.open(QIODevice::ReadOnly)) {
  1926. return;
  1927. }
  1928. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  1929. if (!doc.isObject()) {
  1930. return;
  1931. }
  1932. const QJsonArray provinces = doc.object().value("provinces").toArray();
  1933. for (const auto &prov_val : provinces) {
  1934. const QJsonObject prov = prov_val.toObject();
  1935. QVariantMap entry;
  1936. entry.insert(QStringLiteral("id"), prov.value("id").toString());
  1937. entry.insert(QStringLiteral("name"), prov.value("name").toString());
  1938. entry.insert(QStringLiteral("owner"), prov.value("owner").toString());
  1939. const QJsonArray label_uv = prov.value("label_uv").toArray();
  1940. if (label_uv.size() >= 2) {
  1941. QVariantList label_list;
  1942. label_list.reserve(2);
  1943. label_list.push_back(label_uv.at(0).toDouble());
  1944. label_list.push_back(label_uv.at(1).toDouble());
  1945. entry.insert(QStringLiteral("label_uv"), label_list);
  1946. }
  1947. const QJsonArray cities = prov.value("cities").toArray();
  1948. QVariantList city_list;
  1949. city_list.reserve(cities.size());
  1950. for (const auto &city_val : cities) {
  1951. const QJsonObject city = city_val.toObject();
  1952. const QString name = city.value("name").toString();
  1953. const QJsonArray uv = city.value("uv").toArray();
  1954. if (name.isEmpty() || uv.size() < 2) {
  1955. continue;
  1956. }
  1957. QVariantList uv_list;
  1958. uv_list.reserve(2);
  1959. uv_list.push_back(uv.at(0).toDouble());
  1960. uv_list.push_back(uv.at(1).toDouble());
  1961. QVariantMap city_entry;
  1962. city_entry.insert(QStringLiteral("name"), name);
  1963. city_entry.insert(QStringLiteral("uv"), uv_list);
  1964. city_list.push_back(city_entry);
  1965. }
  1966. entry.insert(QStringLiteral("cities"), city_list);
  1967. m_province_labels.push_back(entry);
  1968. }
  1969. if (!m_province_overrides.isEmpty()) {
  1970. QVariantList updated;
  1971. updated.reserve(m_province_labels.size());
  1972. for (const auto &entry_val : m_province_labels) {
  1973. QVariantMap entry = entry_val.toMap();
  1974. const QString id = entry.value(QStringLiteral("id")).toString();
  1975. const auto it = m_province_overrides.find(id);
  1976. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  1977. entry.insert(QStringLiteral("owner"), it->owner);
  1978. }
  1979. updated.push_back(entry);
  1980. }
  1981. m_province_labels = std::move(updated);
  1982. }
  1983. emit province_labels_changed();
  1984. }
  1985. QVariantList CampaignMapView::province_labels() {
  1986. load_province_labels();
  1987. return m_province_labels;
  1988. }
  1989. void CampaignMapView::apply_province_state(const QVariantList &states) {
  1990. QHash<QString, ProvinceVisual> next_overrides;
  1991. next_overrides.reserve(states.size());
  1992. for (const auto &state_val : states) {
  1993. const QVariantMap state = state_val.toMap();
  1994. const QString id = state.value(QStringLiteral("id")).toString();
  1995. if (id.isEmpty()) {
  1996. continue;
  1997. }
  1998. ProvinceVisual visual;
  1999. visual.owner = state.value(QStringLiteral("owner")).toString();
  2000. const QVariantList color_list =
  2001. state.value(QStringLiteral("color")).toList();
  2002. if (color_list.size() >= 4) {
  2003. visual.color = QVector4D(static_cast<float>(color_list.at(0).toDouble()),
  2004. static_cast<float>(color_list.at(1).toDouble()),
  2005. static_cast<float>(color_list.at(2).toDouble()),
  2006. static_cast<float>(color_list.at(3).toDouble()));
  2007. visual.has_color = true;
  2008. }
  2009. next_overrides.insert(id, visual);
  2010. }
  2011. m_province_overrides = std::move(next_overrides);
  2012. ++m_province_state_version;
  2013. if (m_provinces_loaded) {
  2014. for (auto &province : m_provinces) {
  2015. const auto it = m_province_overrides.find(province.id);
  2016. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2017. province.owner = it->owner;
  2018. }
  2019. }
  2020. }
  2021. if (m_province_labels_loaded) {
  2022. QVariantList updated;
  2023. updated.reserve(m_province_labels.size());
  2024. for (const auto &entry_val : m_province_labels) {
  2025. QVariantMap entry = entry_val.toMap();
  2026. const QString id = entry.value(QStringLiteral("id")).toString();
  2027. const auto it = m_province_overrides.find(id);
  2028. if (it != m_province_overrides.end() && !it->owner.isEmpty()) {
  2029. entry.insert(QStringLiteral("owner"), it->owner);
  2030. }
  2031. updated.push_back(entry);
  2032. }
  2033. m_province_labels = std::move(updated);
  2034. emit province_labels_changed();
  2035. }
  2036. update();
  2037. }
  2038. QString CampaignMapView::province_at_screen(float x, float y) {
  2039. load_provinces_for_hit_test();
  2040. if (m_provinces.empty()) {
  2041. return {};
  2042. }
  2043. const float w = static_cast<float>(width());
  2044. const float h = static_cast<float>(height());
  2045. if (w <= 0.0F || h <= 0.0F) {
  2046. return {};
  2047. }
  2048. const float ndc_x = (2.0F * x / w) - 1.0F;
  2049. const float ndc_y = 1.0F - (2.0F * y / h);
  2050. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2051. m_orbit_distance, m_pan_u, m_pan_v);
  2052. bool inverted = false;
  2053. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2054. if (!inverted) {
  2055. return {};
  2056. }
  2057. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2058. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2059. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2060. return {};
  2061. }
  2062. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2063. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2064. const QVector3D dir = far_v - near_v;
  2065. if (qFuzzyIsNull(dir.y())) {
  2066. return {};
  2067. }
  2068. const float t = -near_v.y() / dir.y();
  2069. if (t < 0.0F) {
  2070. return {};
  2071. }
  2072. const QVector3D hit = near_v + dir * t;
  2073. const float u = 1.0F - hit.x();
  2074. const float v = hit.z();
  2075. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2076. return {};
  2077. }
  2078. const QVector2D p(u, v);
  2079. for (const auto &province : m_provinces) {
  2080. const auto &triangles = province.triangles;
  2081. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2082. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2083. triangles[i + 2])) {
  2084. return province.id;
  2085. }
  2086. }
  2087. }
  2088. return {};
  2089. }
  2090. QVariantMap CampaignMapView::province_info_at_screen(float x, float y) {
  2091. load_provinces_for_hit_test();
  2092. QVariantMap info;
  2093. if (m_provinces.empty()) {
  2094. return info;
  2095. }
  2096. const float w = static_cast<float>(width());
  2097. const float h = static_cast<float>(height());
  2098. if (w <= 0.0F || h <= 0.0F) {
  2099. return info;
  2100. }
  2101. const float ndc_x = (2.0F * x / w) - 1.0F;
  2102. const float ndc_y = 1.0F - (2.0F * y / h);
  2103. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2104. m_orbit_distance, m_pan_u, m_pan_v);
  2105. bool inverted = false;
  2106. const QMatrix4x4 inv = mvp.inverted(&inverted);
  2107. if (!inverted) {
  2108. return info;
  2109. }
  2110. QVector4D near_p = inv * QVector4D(ndc_x, ndc_y, -1.0F, 1.0F);
  2111. QVector4D far_p = inv * QVector4D(ndc_x, ndc_y, 1.0F, 1.0F);
  2112. if (qFuzzyIsNull(near_p.w()) || qFuzzyIsNull(far_p.w())) {
  2113. return info;
  2114. }
  2115. QVector3D near_v = QVector3D(near_p.x(), near_p.y(), near_p.z()) / near_p.w();
  2116. QVector3D far_v = QVector3D(far_p.x(), far_p.y(), far_p.z()) / far_p.w();
  2117. const QVector3D dir = far_v - near_v;
  2118. if (qFuzzyIsNull(dir.y())) {
  2119. return info;
  2120. }
  2121. const float t = -near_v.y() / dir.y();
  2122. if (t < 0.0F) {
  2123. return info;
  2124. }
  2125. const QVector3D hit = near_v + dir * t;
  2126. const float u = 1.0F - hit.x();
  2127. const float v = hit.z();
  2128. if (u < 0.0F || u > 1.0F || v < 0.0F || v > 1.0F) {
  2129. return info;
  2130. }
  2131. const QVector2D p(u, v);
  2132. for (const auto &province : m_provinces) {
  2133. const auto &triangles = province.triangles;
  2134. for (size_t i = 0; i + 2 < triangles.size(); i += 3) {
  2135. if (point_in_triangle(p, triangles[i], triangles[i + 1],
  2136. triangles[i + 2])) {
  2137. info.insert(QStringLiteral("id"), province.id);
  2138. info.insert(QStringLiteral("name"), province.name);
  2139. info.insert(QStringLiteral("owner"), province.owner);
  2140. return info;
  2141. }
  2142. }
  2143. }
  2144. return info;
  2145. }
  2146. QPointF CampaignMapView::screen_pos_for_uv(float u, float v) {
  2147. const float w = static_cast<float>(width());
  2148. const float h = static_cast<float>(height());
  2149. if (w <= 0.0F || h <= 0.0F) {
  2150. return {};
  2151. }
  2152. const float clamped_u = qBound(0.0F, u, 1.0F);
  2153. const float clamped_v = qBound(0.0F, v, 1.0F);
  2154. const QMatrix4x4 mvp = build_mvp_matrix(w, h, m_orbit_yaw, m_orbit_pitch,
  2155. m_orbit_distance, m_pan_u, m_pan_v);
  2156. const QVector4D world(1.0F - clamped_u, 0.0F, clamped_v, 1.0F);
  2157. const QVector4D clip = mvp * world;
  2158. if (qFuzzyIsNull(clip.w())) {
  2159. return {};
  2160. }
  2161. const float ndc_x = clip.x() / clip.w();
  2162. const float ndc_y = clip.y() / clip.w();
  2163. const float screen_x = (ndc_x + 1.0F) * 0.5F * w;
  2164. const float screen_y = (1.0F - (ndc_y + 1.0F) * 0.5F) * h;
  2165. return QPointF(screen_x, screen_y);
  2166. }
  2167. void CampaignMapView::load_hannibal_paths() {
  2168. if (m_hannibal_paths_loaded) {
  2169. return;
  2170. }
  2171. m_hannibal_paths_loaded = true;
  2172. m_hannibal_paths.clear();
  2173. const QString path = Utils::Resources::resolveResourcePath(
  2174. QStringLiteral(":/assets/campaign_map/hannibal_path.json"));
  2175. QFile file(path);
  2176. if (!file.open(QIODevice::ReadOnly)) {
  2177. qWarning() << "Failed to load Hannibal paths from" << path;
  2178. return;
  2179. }
  2180. const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
  2181. if (!doc.isObject()) {
  2182. return;
  2183. }
  2184. const QJsonArray lines = doc.object().value("lines").toArray();
  2185. for (const auto &line_val : lines) {
  2186. const QJsonArray line = line_val.toArray();
  2187. std::vector<QVector2D> path;
  2188. path.reserve(static_cast<size_t>(line.size()));
  2189. for (const auto &pt_val : line) {
  2190. const QJsonArray pt = pt_val.toArray();
  2191. if (pt.size() < 2) {
  2192. continue;
  2193. }
  2194. path.emplace_back(static_cast<float>(pt.at(0).toDouble()),
  2195. static_cast<float>(pt.at(1).toDouble()));
  2196. }
  2197. if (!path.empty()) {
  2198. m_hannibal_paths.push_back(std::move(path));
  2199. }
  2200. }
  2201. }
  2202. QPointF CampaignMapView::hannibal_icon_position() {
  2203. load_hannibal_paths();
  2204. if (m_hannibal_paths.empty()) {
  2205. return {};
  2206. }
  2207. const int mission_idx = qBound(0, m_current_mission,
  2208. static_cast<int>(m_hannibal_paths.size()) - 1);
  2209. const auto &path = m_hannibal_paths[static_cast<size_t>(mission_idx)];
  2210. if (path.empty()) {
  2211. return {};
  2212. }
  2213. const QVector2D &endpoint = path.back();
  2214. return screen_pos_for_uv(endpoint.x(), endpoint.y());
  2215. }
  2216. void CampaignMapView::set_orbit_yaw(float yaw) {
  2217. if (qFuzzyCompare(m_orbit_yaw, yaw)) {
  2218. return;
  2219. }
  2220. m_orbit_yaw = yaw;
  2221. emit orbit_yaw_changed();
  2222. update();
  2223. }
  2224. void CampaignMapView::set_orbit_pitch(float pitch) {
  2225. const float clamped = qBound(5.0F, pitch, 90.0F);
  2226. if (qFuzzyCompare(m_orbit_pitch, clamped)) {
  2227. return;
  2228. }
  2229. m_orbit_pitch = clamped;
  2230. emit orbit_pitch_changed();
  2231. update();
  2232. }
  2233. void CampaignMapView::set_orbit_distance(float distance) {
  2234. const float clamped =
  2235. qBound(k_min_orbit_distance, distance, k_max_orbit_distance);
  2236. if (qFuzzyCompare(m_orbit_distance, clamped)) {
  2237. return;
  2238. }
  2239. m_orbit_distance = clamped;
  2240. emit orbit_distance_changed();
  2241. update();
  2242. }
  2243. void CampaignMapView::set_pan_u(float pan) {
  2244. const float clamped = qBound(-0.5F, pan, 0.5F);
  2245. if (qFuzzyCompare(m_pan_u, clamped)) {
  2246. return;
  2247. }
  2248. m_pan_u = clamped;
  2249. emit pan_u_changed();
  2250. update();
  2251. }
  2252. void CampaignMapView::set_pan_v(float pan) {
  2253. const float clamped = qBound(-0.5F, pan, 0.5F);
  2254. if (qFuzzyCompare(m_pan_v, clamped)) {
  2255. return;
  2256. }
  2257. m_pan_v = clamped;
  2258. emit pan_v_changed();
  2259. update();
  2260. }
  2261. void CampaignMapView::set_hover_province_id(const QString &province_id) {
  2262. if (m_hover_province_id == province_id) {
  2263. return;
  2264. }
  2265. m_hover_province_id = province_id;
  2266. emit hover_province_id_changed();
  2267. update();
  2268. }
  2269. void CampaignMapView::set_current_mission(int mission) {
  2270. const int clamped = qBound(0, mission, 7);
  2271. if (m_current_mission == clamped) {
  2272. return;
  2273. }
  2274. m_current_mission = clamped;
  2275. emit current_mission_changed();
  2276. update();
  2277. }
  2278. void CampaignMapView::set_terrain_height_scale(float scale) {
  2279. if (qFuzzyCompare(m_terrain_height_scale, scale)) {
  2280. return;
  2281. }
  2282. m_terrain_height_scale = scale;
  2283. emit terrain_height_scale_changed();
  2284. update();
  2285. }
  2286. void CampaignMapView::set_show_province_fills(bool show) {
  2287. if (m_show_province_fills == show) {
  2288. return;
  2289. }
  2290. m_show_province_fills = show;
  2291. emit show_province_fills_changed();
  2292. update();
  2293. }
  2294. auto CampaignMapView::createRenderer() const -> Renderer * {
  2295. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  2296. if ((ctx == nullptr) || !ctx->isValid()) {
  2297. qCritical()
  2298. << "CampaignMapView::createRenderer() - No valid OpenGL context";
  2299. qCritical()
  2300. << "Running in software rendering mode - map view not available";
  2301. return nullptr;
  2302. }
  2303. return new CampaignMapRenderer();
  2304. }