map-editor.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. hex.addEventListener('click', (e) => {
  109. e.stopPropagation();
  110. this.selectTile(q, r);
  111. });
  112. hex.addEventListener('mouseenter', () => {
  113. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  114. hex.style.backgroundColor = '#e3f2fd';
  115. }
  116. });
  117. hex.addEventListener('mouseleave', () => {
  118. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  119. hex.style.backgroundColor = '#ffffff';
  120. }
  121. });
  122. this.canvas.appendChild(hex);
  123. }
  124. selectTile(q, r) {
  125. if (this.selectedTile) {
  126. const prevHex = this.canvas.querySelector(`[data-q="${this.selectedTile.q}"][data-r="${this.selectedTile.r}"]`);
  127. if (prevHex) {
  128. prevHex.style.backgroundColor = '#ffffff';
  129. prevHex.style.borderColor = '#666';
  130. }
  131. }
  132. this.selectedTile = { q, r };
  133. const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
  134. if (hex) {
  135. hex.style.backgroundColor = '#2196f3';
  136. hex.style.borderColor = '#1976d2';
  137. }
  138. // Émettre un événement DOM global pour signaler la sélection
  139. try {
  140. const ev = new CustomEvent('mg:tileSelected', { detail: { q, r } });
  141. window.dispatchEvent(ev);
  142. } catch (e) {
  143. // ignore
  144. }
  145. this.showTileInfo(q, r);
  146. }
  147. showTileInfo(q, r) {
  148. const tileInfo = document.getElementById('tileInfo');
  149. const tilePosition = document.getElementById('tilePosition');
  150. const tileType = document.getElementById('tileType');
  151. const tileProperties = document.getElementById('tileProperties');
  152. tilePosition.textContent = `Q: ${q}, R: ${r}`;
  153. // récupérer le type si défini dans mapData.tiles ou fallback
  154. let type = 'Vide';
  155. try {
  156. if (window.mapData && window.mapData.tiles) {
  157. const key = `${q},${r}`;
  158. const t = window.mapData.tiles[key] || (window.mapData.tiles[q] && window.mapData.tiles[q][r]);
  159. if (t && t.type) type = t.type;
  160. }
  161. } catch (e) {
  162. // ignore
  163. }
  164. tileType.textContent = type;
  165. // Montrer la sidebar des types de tuile
  166. const tileTypeTool = document.getElementById('tile-type-tool');
  167. if (tileTypeTool) tileTypeTool.style.display = 'block';
  168. // émettre événement tileInfo affiché
  169. try { window.dispatchEvent(new CustomEvent('mg:tileInfoShown', { detail: { q, r, type } })); } catch (e) {}
  170. tileProperties.innerHTML = `...`;
  171. tileInfo.style.display = 'block';
  172. }
  173. setupEventListeners() {
  174. document.getElementById('zoomIn').addEventListener('click', (e) => { e.preventDefault(); this.zoom(1.2); });
  175. document.getElementById('zoomOut').addEventListener('click', (e) => { e.preventDefault(); this.zoom(0.8); });
  176. document.getElementById('fitToScreen').addEventListener('click', (e) => { e.preventDefault(); this.fitToScreen(); });
  177. this.container.addEventListener('mousedown', (e) => {
  178. if (e.target === this.container) {
  179. this.isDragging = true;
  180. this.lastMousePos = { x: e.clientX, y: e.clientY };
  181. this.canvas.style.cursor = 'grabbing';
  182. }
  183. });
  184. document.addEventListener('mousemove', (e) => {
  185. if (this.isDragging) {
  186. const deltaX = e.clientX - this.lastMousePos.x;
  187. const deltaY = e.clientY - this.lastMousePos.y;
  188. this.panOffset.x += deltaX;
  189. this.panOffset.y += deltaY;
  190. this.updateTransform();
  191. this.lastMousePos = { x: e.clientX, y: e.clientY };
  192. }
  193. });
  194. document.addEventListener('mouseup', () => { this.isDragging = false; this.canvas.style.cursor = 'grab'; });
  195. this.container.addEventListener('click', () => {
  196. if (this.selectedTile) { this.selectTile(null, null); document.getElementById('tileInfo').style.display = 'none'; }
  197. });
  198. }
  199. zoom(factor) {
  200. if (window.MG && window.MG.geom && typeof window.MG.geom.computeZoom === 'function') {
  201. this.zoomLevel = window.MG.geom.computeZoom(this.zoomLevel, factor);
  202. } else {
  203. this.zoomLevel *= factor;
  204. this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel));
  205. }
  206. this.updateTransform();
  207. const el = document.getElementById('zoomLevel'); if (el) el.textContent = Math.round(this.zoomLevel * 100);
  208. }
  209. 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); }
  210. 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})`; }
  211. hideLoading() { const loading = document.getElementById('mapLoading'); if (loading) { loading.classList.remove('d-flex'); loading.style.display = 'none'; } }
  212. }
  213. // Initialiser l'éditeur
  214. (function() {
  215. function initMapEditor() {
  216. try { new MapEditor(); } catch (error) { console.error('Erreur lors de la création de MapEditor:', error); }
  217. }
  218. if (document.readyState === 'loading') {
  219. document.addEventListener('DOMContentLoaded', function(){ if (document.getElementById('mapCanvas')) initMapEditor(); });
  220. } else {
  221. if (document.getElementById('mapCanvas')) initMapEditor();
  222. }
  223. })();
  224. // --- Fin du code MapEditor ---
  225. });
  226. })();
  227. // Listeners pour la sidebar (gestion des types de tuile)
  228. (function(){
  229. function onTypeClick(e){
  230. const btn = e.currentTarget;
  231. const type = btn.dataset.type;
  232. // Mettre à jour l'affichage dans #tileType
  233. const tileTypeEl = document.getElementById('tileType');
  234. if (tileTypeEl) tileTypeEl.textContent = type;
  235. // Si une tuile est sélectionnée on met à jour window.mapData (structure minimale)
  236. try {
  237. const selected = (window.MG && window.MG.selectedTile) || null;
  238. // Certains setups n'exposent pas MG.selectedTile. On récupère depuis l'événement global si nécessaire
  239. let q=null,r=null;
  240. if (selected && typeof selected.q !== 'undefined') { q=selected.q; r=selected.r; }
  241. // fallback: chercher un élément hexagon sélectionné
  242. if (q===null) {
  243. const el = document.querySelector('.hexagon[style*="background-color: rgb(33, 150, 243)"]') || document.querySelector('.hexagon[style*="#2196f3"]');
  244. if (el) { q = parseInt(el.dataset.q,10); r = parseInt(el.dataset.r,10); }
  245. }
  246. if (q!==null && typeof q !== 'undefined'){
  247. window.mapData = window.mapData || {};
  248. window.mapData.tiles = window.mapData.tiles || {};
  249. const key = `${q},${r}`;
  250. window.mapData.tiles[key] = window.mapData.tiles[key] || {};
  251. window.mapData.tiles[key].type = type;
  252. // Dispatch event pour signaler changement de type
  253. try { window.dispatchEvent(new CustomEvent('mg:tileTypeChanged', { detail: { q, r, type } })); } catch(e){}
  254. }
  255. } catch (err){ console.error('Erreur lors du changement de type de tuile', err); }
  256. }
  257. document.addEventListener('DOMContentLoaded', function(){
  258. const opts = document.querySelectorAll('.tile-type-option');
  259. opts.forEach(o => o.addEventListener('click', onTypeClick));
  260. // Écouter la sélection de tuile pour stocker la sélection dans MG.selectedTile si possible
  261. window.addEventListener('mg:tileSelected', function(ev){
  262. try { window.MG = window.MG || {}; window.MG.selectedTile = ev.detail; } catch(e){}
  263. });
  264. });
  265. })();