map-editor.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. (function(){
  2. var domReady = (window.MG && window.MG.domReady) || window.__MG_domReady || function(cb){ if (document.readyState==='loading') document.addEventListener('DOMContentLoaded', cb); else cb(); };
  3. domReady(function(){
  4. // On attend que la variable mapData soit définie dans la vue (home.php injecte mapData)
  5. if (typeof window.mapData === 'undefined' && typeof mapData !== 'undefined') {
  6. window.mapData = mapData;
  7. }
  8. // Guard: si pas de mapData ou pas d'élément canvas, ne pas initialiser l'éditeur
  9. if (typeof window.mapData === 'undefined' || !document.getElementById('mapCanvas')) {
  10. // Rien à faire sur cette page
  11. return;
  12. }
  13. // --- Début du code de MapEditor (copié depuis l'ancien fichier non-modulaire) ---
  14. class MapEditor {
  15. constructor() {
  16. this.canvas = document.getElementById('mapCanvas');
  17. this.container = document.querySelector('.map-canvas-container');
  18. this.zoomLevel = 1;
  19. this.panOffset = { x: 0, y: 0 };
  20. this.isDragging = false;
  21. this.lastMousePos = { x: 0, y: 0 };
  22. this.selectedTile = null;
  23. this.tileSize = 50; // Rayon de l'hexagone (du centre au sommet)
  24. this.init();
  25. }
  26. init() {
  27. if (!this.canvas) {
  28. console.error('MapEditor: Élément canvas non trouvé!');
  29. return;
  30. }
  31. if (!this.container) {
  32. console.error('MapEditor: Conteneur non trouvé!');
  33. return;
  34. }
  35. this.setupCanvas();
  36. this.renderMap();
  37. this.setupEventListeners();
  38. this.hideLoading();
  39. this.fitToScreen();
  40. }
  41. setupCanvas() {
  42. this.canvas.style.transformOrigin = '0 0';
  43. }
  44. axialToPixel(q, r) {
  45. if (window.MG && window.MG.geom && typeof window.MG.geom.axialToPixel === 'function') {
  46. return window.MG.geom.axialToPixel(this.tileSize, q, r);
  47. }
  48. // fallback local implementation
  49. const size = this.tileSize;
  50. const x = size * Math.sqrt(3) * (q + r / 2);
  51. const y = size * 1.5 * r;
  52. return { x, y };
  53. }
  54. renderMap() {
  55. this.canvas.innerHTML = '';
  56. const hexWidth = this.tileSize * Math.sqrt(3);
  57. const hexHeight = this.tileSize * 2;
  58. const mapWidth = (window.mapData && window.mapData.width) || 5;
  59. const mapHeight = (window.mapData && window.mapData.height) || 5;
  60. const radius = Math.floor((Math.min(mapWidth, mapHeight) - 1) / 2);
  61. if (radius < 0) return;
  62. const positions = [];
  63. let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  64. for (let q = -radius; q <= radius; q++) {
  65. const rMin = Math.max(-radius, -q - radius);
  66. const rMax = Math.min(radius, -q + radius);
  67. for (let r = rMin; r <= rMax; r++) {
  68. const { x, y } = this.axialToPixel(q, r);
  69. positions.push({ q, r, x, y });
  70. const halfW = hexWidth / 2;
  71. const halfH = hexHeight / 2;
  72. if (x - halfW < minX) minX = x - halfW;
  73. if (y - halfH < minY) minY = y - halfH;
  74. if (x + halfW > maxX) maxX = x + halfW;
  75. if (y + halfH > maxY) maxY = y + halfH;
  76. }
  77. }
  78. const padding = 20;
  79. const canvasWidth = (maxX - minX) + hexWidth + padding;
  80. const canvasHeight = (maxY - minY) + hexHeight + padding;
  81. this.canvas.style.width = canvasWidth + 'px';
  82. this.canvas.style.height = canvasHeight + 'px';
  83. const offsetX = -minX + padding / 2;
  84. const offsetY = -minY + padding / 2;
  85. for (const pos of positions) {
  86. this.renderHexagon(pos.q, pos.r, pos.x + offsetX, pos.y + offsetY, hexWidth, hexHeight);
  87. }
  88. }
  89. renderHexagon(q, r, x, y, hexWidth, hexHeight) {
  90. const hex = document.createElement('div');
  91. hex.className = 'hexagon';
  92. hex.dataset.q = q;
  93. hex.dataset.r = r;
  94. const expansion = Math.round(hexWidth * 0.004 * 1000) / 1000;
  95. const adjWidth = hexWidth + expansion;
  96. const adjHeight = hexHeight + expansion;
  97. const halfW = adjWidth / 2;
  98. const halfH = adjHeight / 2;
  99. hex.style.width = adjWidth + 'px';
  100. hex.style.height = adjHeight + 'px';
  101. hex.style.left = (Math.round((x - halfW) * 1000) / 1000) + 'px';
  102. hex.style.top = (Math.round((y - halfH) * 1000) / 1000) + 'px';
  103. hex.style.position = 'absolute';
  104. hex.style.cursor = 'pointer';
  105. hex.style.transition = 'background-color 0.2s';
  106. hex.style.backgroundColor = '#ffffff';
  107. hex.style.clipPath = 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)';
  108. // Ajouter le SVG selon le type de tuile
  109. this.updateHexagonContent(hex, q, r);
  110. hex.addEventListener('click', (e) => {
  111. e.stopPropagation();
  112. this.selectTile(q, r);
  113. });
  114. hex.addEventListener('mouseenter', () => {
  115. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  116. hex.style.backgroundColor = '#e3f2fd';
  117. }
  118. });
  119. hex.addEventListener('mouseleave', () => {
  120. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  121. hex.style.backgroundColor = '#ffffff';
  122. }
  123. });
  124. this.canvas.appendChild(hex);
  125. }
  126. updateHexagonContent(hex, q, r) {
  127. // Récupérer le type de tuile
  128. let type = null;
  129. try {
  130. if (window.mapData && window.mapData.tiles) {
  131. const key = `${q},${r}`;
  132. const tileData = window.mapData.tiles[key];
  133. if (tileData && tileData.type) {
  134. type = tileData.type;
  135. }
  136. }
  137. } catch (e) {
  138. // ignore
  139. }
  140. // Si pas de type spécifique, chercher dans mapData.hexes
  141. if (!type) {
  142. if (window.mapData && window.mapData.hexes) {
  143. const hexData = window.mapData.hexes.find(h => h.q === q && h.r === r);
  144. if (hexData && hexData.tile && hexData.tile.type) {
  145. type = hexData.tile.type;
  146. }
  147. }
  148. }
  149. if (!type || type === 'empty') {
  150. type = 'empty';
  151. }
  152. // Trouver la définition de tuile
  153. let tileDef = null;
  154. if (window.templateData && window.templateData.tileDefinitions) {
  155. tileDef = window.templateData.tileDefinitions.find(def => def.id === type);
  156. }
  157. if (tileDef && tileDef.asset) {
  158. // Utiliser l'asset SVG comme background
  159. hex.style.backgroundColor = 'transparent';
  160. hex.style.backgroundImage = `url('${tileDef.asset}')`;
  161. hex.style.backgroundSize = 'contain';
  162. hex.style.backgroundPosition = 'center';
  163. hex.style.filter = 'none';
  164. } else {
  165. // Utiliser la couleur par défaut
  166. const color = tileDef && tileDef.color ? tileDef.color : '#ffffff';
  167. hex.style.backgroundColor = color;
  168. hex.style.backgroundImage = 'none';
  169. hex.style.filter = 'none';
  170. }
  171. }
  172. selectTile(q, r) {
  173. if (this.selectedTile) {
  174. const prevHex = this.canvas.querySelector(`[data-q="${this.selectedTile.q}"][data-r="${this.selectedTile.r}"]`);
  175. if (prevHex) {
  176. prevHex.style.backgroundColor = '#ffffff';
  177. prevHex.style.borderColor = '#666';
  178. }
  179. }
  180. this.selectedTile = { q, r };
  181. const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
  182. if (hex) {
  183. hex.style.backgroundColor = '#2196f3';
  184. hex.style.borderColor = '#1976d2';
  185. }
  186. // Émettre un événement DOM global pour signaler la sélection
  187. try {
  188. const ev = new CustomEvent('mg:tileSelected', { detail: { q, r } });
  189. window.dispatchEvent(ev);
  190. } catch (e) {
  191. // ignore
  192. }
  193. this.showTileInfo(q, r);
  194. }
  195. showTileInfo(q, r) {
  196. const tileInfo = document.getElementById('tileInfo');
  197. const tilePosition = document.getElementById('tilePosition');
  198. const tileType = document.getElementById('tileType');
  199. const tileProperties = document.getElementById('tileProperties');
  200. tilePosition.textContent = `Q: ${q}, R: ${r}`;
  201. // récupérer le type si défini dans mapData.tiles ou fallback
  202. let type = 'Vide';
  203. try {
  204. if (window.mapData && window.mapData.tiles) {
  205. const key = `${q},${r}`;
  206. const t = window.mapData.tiles[key] || (window.mapData.tiles[q] && window.mapData.tiles[q][r]);
  207. if (t && t.type) type = t.type;
  208. }
  209. } catch (e) {
  210. // ignore
  211. }
  212. tileType.textContent = type;
  213. // Montrer la sidebar des types de tuile
  214. const tileTypeTool = document.getElementById('tile-type-tool');
  215. if (tileTypeTool) tileTypeTool.style.display = 'block';
  216. // émettre événement tileInfo affiché
  217. try { window.dispatchEvent(new CustomEvent('mg:tileInfoShown', { detail: { q, r, type } })); } catch (e) {}
  218. tileProperties.innerHTML = `...`;
  219. tileInfo.style.display = 'block';
  220. }
  221. setupEventListeners() {
  222. document.getElementById('zoomIn').addEventListener('click', (e) => { e.preventDefault(); this.zoom(1.2); });
  223. document.getElementById('zoomOut').addEventListener('click', (e) => { e.preventDefault(); this.zoom(0.8); });
  224. document.getElementById('fitToScreen').addEventListener('click', (e) => { e.preventDefault(); this.fitToScreen(); });
  225. this.container.addEventListener('mousedown', (e) => {
  226. if (e.target === this.container) {
  227. this.isDragging = true;
  228. this.lastMousePos = { x: e.clientX, y: e.clientY };
  229. this.canvas.style.cursor = 'grabbing';
  230. }
  231. });
  232. document.addEventListener('mousemove', (e) => {
  233. if (this.isDragging) {
  234. const deltaX = e.clientX - this.lastMousePos.x;
  235. const deltaY = e.clientY - this.lastMousePos.y;
  236. this.panOffset.x += deltaX;
  237. this.panOffset.y += deltaY;
  238. this.updateTransform();
  239. this.lastMousePos = { x: e.clientX, y: e.clientY };
  240. }
  241. });
  242. document.addEventListener('mouseup', () => { this.isDragging = false; this.canvas.style.cursor = 'grab'; });
  243. this.container.addEventListener('click', () => {
  244. if (this.selectedTile) { this.selectTile(null, null); document.getElementById('tileInfo').style.display = 'none'; }
  245. });
  246. }
  247. zoom(factor) {
  248. if (window.MG && window.MG.geom && typeof window.MG.geom.computeZoom === 'function') {
  249. this.zoomLevel = window.MG.geom.computeZoom(this.zoomLevel, factor);
  250. } else {
  251. this.zoomLevel *= factor;
  252. this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel));
  253. }
  254. this.updateTransform();
  255. const el = document.getElementById('zoomLevel'); if (el) el.textContent = Math.round(this.zoomLevel * 100);
  256. }
  257. fitToScreen() { const containerRect = this.container.getBoundingClientRect(); const canvasRect = this.canvas.getBoundingClientRect(); const scaleX = containerRect.width / canvasRect.width; const scaleY = containerRect.height / canvasRect.height; const scale = Math.min(scaleX, scaleY) * 0.9; this.zoomLevel = scale; this.panOffset = { x: 0, y: 0 }; this.updateTransform(); document.getElementById('zoomLevel').textContent = Math.round(this.zoomLevel * 100); }
  258. updateTransform() { const tx = Math.round(this.panOffset.x); const ty = Math.round(this.panOffset.y); this.canvas.style.transform = `translate(${tx}px, ${ty}px) scale(${this.zoomLevel})`; }
  259. hideLoading() { const loading = document.getElementById('mapLoading'); if (loading) { loading.classList.remove('d-flex'); loading.style.display = 'none'; } }
  260. }
  261. // Initialiser l'éditeur
  262. (function() {
  263. function initMapEditor() {
  264. try { new MapEditor(); } catch (error) { console.error('Erreur lors de la création de MapEditor:', error); }
  265. }
  266. if (document.readyState === 'loading') {
  267. document.addEventListener('DOMContentLoaded', function(){ if (document.getElementById('mapCanvas')) initMapEditor(); });
  268. } else {
  269. if (document.getElementById('mapCanvas')) initMapEditor();
  270. }
  271. })();
  272. // --- Fin du code MapEditor ---
  273. });
  274. })();
  275. // Listeners pour la sidebar (gestion des types de tuile)
  276. (function(){
  277. function onTypeClick(e){
  278. const input = e.currentTarget;
  279. const type = input.value;
  280. // Mettre à jour l'affichage dans #tileType
  281. const tileTypeEl = document.getElementById('tileType');
  282. if (tileTypeEl) tileTypeEl.textContent = type;
  283. // Si une tuile est sélectionnée on met à jour window.mapData (structure minimale)
  284. try {
  285. const selected = (window.MG && window.MG.selectedTile) || null;
  286. // Certains setups n'exposent pas MG.selectedTile. On récupère depuis l'événement global si nécessaire
  287. let q=null,r=null;
  288. if (selected && typeof selected.q !== 'undefined') { q=selected.q; r=selected.r; }
  289. // fallback: chercher un élément hexagon sélectionné
  290. if (q===null) {
  291. const el = document.querySelector('.hexagon[style*="background-color: rgb(33, 150, 243)"]') || document.querySelector('.hexagon[style*="#2196f3"]');
  292. if (el) { q = parseInt(el.dataset.q,10); r = parseInt(el.dataset.r,10); }
  293. }
  294. if (q!==null && typeof q !== 'undefined'){
  295. window.mapData = window.mapData || {};
  296. window.mapData.tiles = window.mapData.tiles || {};
  297. const key = `${q},${r}`;
  298. window.mapData.tiles[key] = window.mapData.tiles[key] || {};
  299. window.mapData.tiles[key].type = type;
  300. // Mettre à jour visuellement la tuile
  301. const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
  302. if (hex) {
  303. updateHexagonContent(hex, q, r);
  304. }
  305. // Dispatch event pour signaler changement de type
  306. try { window.dispatchEvent(new CustomEvent('mg:tileTypeChanged', { detail: { q, r, type } })); } catch(e){}
  307. }
  308. } catch (err){ console.error('Erreur lors du changement de type de tuile', err); }
  309. }
  310. // Fonction pour mettre à jour le contenu d'un hexagone selon son type
  311. function updateHexagonContent(hex, q, r) {
  312. // Récupérer le type de tuile
  313. let type = null;
  314. try {
  315. if (window.mapData && window.mapData.tiles) {
  316. const key = `${q},${r}`;
  317. const tileData = window.mapData.tiles[key];
  318. if (tileData && tileData.type) {
  319. type = tileData.type;
  320. }
  321. }
  322. } catch (e) {
  323. // ignore
  324. }
  325. // Si pas de type spécifique, chercher dans mapData.hexes
  326. if (!type) {
  327. if (window.mapData && window.mapData.hexes) {
  328. const hexData = window.mapData.hexes.find(h => h.q === q && h.r === r);
  329. if (hexData && hexData.tile && hexData.tile.type) {
  330. type = hexData.tile.type;
  331. }
  332. }
  333. }
  334. if (!type || type === 'empty') {
  335. type = 'empty';
  336. }
  337. // Trouver la définition de tuile
  338. let tileDef = null;
  339. if (window.templateData && window.templateData.tileDefinitions) {
  340. tileDef = window.templateData.tileDefinitions.find(def => def.id === type);
  341. }
  342. if (tileDef && tileDef.asset) {
  343. // Utiliser l'asset SVG comme background
  344. hex.style.backgroundColor = 'transparent';
  345. hex.style.backgroundImage = `url('${tileDef.asset}')`;
  346. hex.style.backgroundSize = 'contain';
  347. hex.style.backgroundPosition = 'center';
  348. hex.style.filter = 'none';
  349. } else {
  350. // Utiliser la couleur par défaut
  351. const color = tileDef && tileDef.color ? tileDef.color : '#ffffff';
  352. hex.style.backgroundColor = color;
  353. hex.style.backgroundImage = 'none';
  354. hex.style.filter = 'none';
  355. }
  356. }
  357. // Fonction pour mettre à jour les checkboxes selon le type de la tuile sélectionnée
  358. function updateTileTypeCheckboxes(type) {
  359. const radios = document.querySelectorAll('.tile-type-radio');
  360. radios.forEach(radio => {
  361. radio.checked = (radio.value === type);
  362. });
  363. }
  364. document.addEventListener('DOMContentLoaded', function(){
  365. const opts = document.querySelectorAll('.tile-type-radio');
  366. opts.forEach(o => o.addEventListener('change', onTypeClick));
  367. // Écouter la sélection de tuile pour mettre à jour les checkboxes
  368. window.addEventListener('mg:tileSelected', function(ev){
  369. try {
  370. window.MG = window.MG || {};
  371. window.MG.selectedTile = ev.detail;
  372. // Récupérer le type de la tuile sélectionnée et mettre à jour les checkboxes
  373. const { q, r } = ev.detail;
  374. const key = `${q},${r}`;
  375. const tileData = window.mapData && window.mapData.tiles && window.mapData.tiles[key];
  376. const type = tileData ? tileData.type : 'empty';
  377. updateTileTypeCheckboxes(type);
  378. } catch(e){}
  379. });
  380. // Écouter les changements de type de tuile pour mettre à jour les checkboxes
  381. window.addEventListener('mg:tileTypeChanged', function(ev){
  382. const { type, q, r } = ev.detail;
  383. updateTileTypeCheckboxes(type);
  384. // Mettre à jour visuellement la tuile
  385. const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
  386. if (hex) {
  387. updateHexagonContent(hex, q, r);
  388. }
  389. });
  390. });
  391. })();