Ticket #3258: replay_menu_wip_v5_r16812.patch
File replay_menu_wip_v5_r16812.patch, 64.6 KB (added by , 9 years ago) |
---|
-
binaries/data/mods/public/gui/common/functions_utility.js
81 81 return text; 82 82 83 83 return text.substr(0, 255).replace(/\\/g, "\\\\").replace(/\[/g, "\\["); 84 84 } 85 85 86 //==================================================================== 87 88 function capitalizeFirstLetter(text) { 89 return text.charAt(0).toUpperCase() + text.slice(1); 90 } 91 86 92 // ==================================================================== 87 93 88 94 // Load default player data, for when it's not otherwise specified 89 95 function initPlayerDefaults() 90 96 { -
binaries/data/mods/public/gui/common/functions_utility_loadsave.js
23 23 /** 24 24 * Check the version compatibility between the saved game to be loaded and the engine 25 25 */ 26 26 function hasSameVersion(metadata, engineInfo) 27 27 { 28 return (metadata.version_major == engineInfo.version_major );28 return (metadata.version_major == engineInfo.version_major && metadata.hasOwnProperty("engine_version") && metadata.engine_version == engineInfo.engine_version); 29 29 } 30 30 31 31 /** 32 32 * Check the mod compatibility between the saved game to be loaded and the engine 33 33 */ -
binaries/data/mods/public/gui/gamesetup/gamesetup.js
487 487 } 488 488 Engine.SwitchGuiPage("page_loading.xml", { 489 489 "attribs": g_GameAttributes, 490 490 "isNetworked" : g_IsNetworked, 491 491 "playerAssignments": g_PlayerAssignments, 492 "isController": g_IsController 492 "isController": g_IsController, 493 "g_IsReplay" : false 493 494 }); 494 495 break; 495 496 496 497 case "chat": 497 498 addChatMessage({ "type": "message", "guid": message.guid, "text": message.text }); -
binaries/data/mods/public/gui/page_replay.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <page> 3 <include>common/modern/setup.xml</include> 4 <include>common/modern/styles.xml</include> 5 <include>common/modern/sprites.xml</include> 6 7 <include>common/setup.xml</include> 8 <include>common/sprite1.xml</include> 9 <include>common/styles.xml</include> 10 <include>common/common_sprites.xml</include> 11 <include>common/common_styles.xml</include> 12 13 <include>replay/styles.xml</include> 14 <include>replay/replay.xml</include> 15 </page> -
binaries/data/mods/public/gui/pregame/mainmenu.xml
344 344 Engine.PushGuiPage("page_locale.xml"); 345 345 ]]> 346 346 </action> 347 347 </object> 348 348 349 <object name="submenuReplayButton" 350 type="button" 351 style="StoneButtonFancy" 352 size="0 64 100% 92" 353 tooltip_style="pgToolTip" 354 > 355 <translatableAttribute id="caption">Replay</translatableAttribute> 356 <translatableAttribute id="tooltip">Shows a replay of a past game.</translatableAttribute> 357 <action on="Press"> 358 closeMenu(); 359 Engine.SwitchGuiPage("page_replay.xml"); 360 </action> 361 </object> 362 349 363 <object name="submenuEditorButton" 350 364 style="StoneButtonFancy" 351 365 type="button" 352 size="0 64 100% 92"366 size="0 96 100% 124" 353 367 tooltip_style="pgToolTip" 354 368 > 355 369 <translatableAttribute id="caption">Scenario Editor</translatableAttribute> 356 370 <translatableAttribute id="tooltip">Open the Atlas Scenario Editor in a new window. You can run this more reliably by starting the game with the command-line argument "-editor".</translatableAttribute> 357 371 <action on="Press"> … … 360 374 </object> 361 375 362 376 <object name="submenuWelcomeScreenButton" 363 377 style="StoneButtonFancy" 364 378 type="button" 365 size="0 96 100% 124"379 size="0 128 100% 156" 366 380 tooltip_style="pgToolTip" 367 381 > 368 382 <translatableAttribute id="caption">Welcome Screen</translatableAttribute> 369 383 <translatableAttribute id="tooltip">Show the Welcome Screen. Useful if you hid it by mistake.</translatableAttribute> 370 384 <action on="Press"> … … 375 389 </action> 376 390 </object> 377 391 <object name="submenuModSelection" 378 392 style="StoneButtonFancy" 379 393 type="button" 380 size="0 1 28 100% 156"394 size="0 156 100% 188" 381 395 tooltip_style="pgToolTip" 382 396 > 383 397 <translatableAttribute id="caption">Mod Selection</translatableAttribute> 384 398 <translatableAttribute id="tooltip">Select mods to use.</translatableAttribute> 385 399 <action on="Press"> … … 482 496 > 483 497 <translatableAttribute id="caption">Tools & Options</translatableAttribute> 484 498 <translatableAttribute id="tooltip">Game options and scenario design tools.</translatableAttribute> 485 499 <action on="Press"> 486 500 closeMenu(); 487 openMenu("submenuToolsAndOptions", (this.parent.size.top+this.size.top), (this.size.bottom-this.size.top), 5);501 openMenu("submenuToolsAndOptions", (this.parent.size.top+this.size.top), (this.size.bottom-this.size.top), 6); 488 502 </action> 489 503 </object> 490 504 491 505 <!-- EXIT BUTTON --> 492 506 <object name="menuExitButton" -
binaries/data/mods/public/gui/replay/replay.js
1 var g_Replays = []; // All replays found including metadata 2 var g_ReplaysFiltered = []; // List of replays after filtering 3 var g_Playernames = []; // All playernames of all replays, used for autocomplete 4 var g_ReplayListSortBy = "name"; // Used for sorting 5 var g_ReplayListOrder = -1; // Used for sorting 6 var g_mapSizes = initMapSizes(); 7 var g_CivData = loadCivData(); 8 var g_EngineInfo = Engine.GetEngineInfo(); 9 var g_DefaultPlayerData = initPlayerDefaults(); 10 var g_maxPlayerlistChars = 70; 11 var g_DurationFilterMin = [ 0, 0, 15, 30, 45, 60, 90, 120]; 12 var g_DurationFilterMax = [-1, 15, 30, 45, 60, 90, 120, -1]; 13 14 function init() 15 { 16 loadReplays(); 17 updateReplayList(); 18 } 19 20 function loadReplays() 21 { 22 g_Playernames = []; 23 g_Replays = Engine.GetReplays(); 24 for (let replay of g_Replays) 25 { 26 // TODO: enhancement: remove those copies for better performance 27 replay.settings = replay.attribs.settings; 28 replay.playerData = replay.settings.PlayerData; 29 30 // Use time saved in file, otherwise file mod date 31 replay.timestamp = replay.attribs.hasOwnProperty("timestamp") ? replay.attribs.timestamp : replay.filemod_timestamp; 32 33 // Skirmish maps don't have that attribute 34 if (!replay.settings.hasOwnProperty("Size")) 35 replay.settings.Size = -1; 36 37 for (var i in replay.playerData) 38 { 39 // I've encountered a file where 'null' was added to the playerData array... 40 if (!replay.playerData[i]) 41 { 42 error("Replay " + replay.directory + " has bogus player data!"); 43 continue; 44 } 45 var name = replay.playerData[i].Name; 46 if (g_Playernames.indexOf(name) == -1) 47 g_Playernames.push({"name": name}); 48 } 49 } 50 } 51 52 function updateReplayListOrderSelection() 53 { 54 g_ReplayListSortBy = Engine.GetGUIObjectByName("replaySelection").selected_column; 55 g_ReplayListOrder = Engine.GetGUIObjectByName("replaySelection").selected_column_order; 56 applyFilters(); 57 } 58 59 function updateReplayList() 60 { 61 var replaySelection = Engine.GetGUIObjectByName("replaySelection"); 62 63 // Filters depend on the replay list 64 initFilters(); 65 66 if (g_Replays.length == 0) 67 replaySelection.selected = -1; 68 69 // Sort replays 70 g_Replays.sort(function(a,b) 71 { 72 var cmpA, cmpB; 73 switch (g_ReplayListSortBy) 74 { 75 case 'name': 76 cmpA = a.timestamp; 77 cmpB = b.timestamp; 78 break; 79 case 'duration': 80 cmpA = a.duration; 81 cmpB = b.duration; 82 break; 83 case 'players': 84 cmpA = a.playerData.length; 85 cmpB = b.playerData.length; 86 break; 87 case 'mapName': 88 cmpA = getReplayMapName(a); 89 cmpB = getReplayMapName(b); 90 break; 91 case 'mapSize': 92 cmpA = a.settings.Size; 93 cmpB = b.settings.Size; 94 break; 95 case 'popCapacity': 96 cmpA = a.settings.PopulationCap; 97 cmpB = b.settings.PopulationCap; 98 break; 99 } 100 101 // Sort by selected column 102 if (cmpA < cmpB) 103 return -g_ReplayListOrder; 104 else if (cmpA > cmpB) 105 return g_ReplayListOrder; 106 107 // Sort by date/time as a tiebreaker and keep most recent replays at the top 108 if (a.timestamp < b.timestamp) 109 return 1; 110 else if (a.timestamp > b.timestamp) 111 return -1; 112 113 return 0; 114 }); 115 116 // Filter replays and create GUI list data 117 var replayListLabels = []; 118 var replayListDirectories = []; 119 var list_name = []; 120 var list_players = []; 121 var list_mapName = []; 122 var list_mapSize = []; 123 var list_popCapacity = []; 124 var list_duration = []; 125 g_ReplaysFiltered = []; 126 for (var replay of g_Replays) 127 { 128 if (filterReplay(replay)) 129 continue; 130 131 g_ReplaysFiltered.push(replay); 132 133 // TODO: enhancement: if (settings.GameType != "conquest") use other color 134 135 replayListLabels.push(replay.directory); 136 replayListDirectories.push(replay.directory); 137 138 list_name.push(Greyout(replay, getReplayDateTime(replay))); 139 list_players.push(Greyout(replay, getReplayPlayernames(replay, true))); 140 list_mapName.push(Greyout(replay, getReplayMapName(replay))); 141 list_mapSize.push(Greyout(replay, getReplayMapSizeText(replay.settings.Size))); 142 list_popCapacity.push(Greyout(replay, getReplayPopCap(replay))); 143 list_duration.push(Greyout(replay, getReplayDuration(replay))); 144 } 145 146 // TODO: enhancement: remember last selection, like #3244 147 if (replaySelection.selected >= list_name.length) 148 replaySelection.selected = -1; 149 150 // Update list 151 replaySelection.list_name = list_name; 152 replaySelection.list_players = list_players; 153 replaySelection.list_mapName = list_mapName; 154 replaySelection.list_mapSize = list_mapSize; 155 replaySelection.list_popCapacity = list_popCapacity; 156 replaySelection.list_duration = list_duration; 157 158 replaySelection.list = replayListLabels; 159 replaySelection.list_data = replayListDirectories; 160 } 161 162 function Greyout(replay, text) 163 { 164 if (isReplayCompatible(replay)) 165 return text; 166 else 167 return '[color="128 128 128"]' + text + '[/color]'; 168 } 169 170 function getReplayDateTime(replay) 171 { 172 return Engine.FormatMillisecondsIntoDateString(replay.timestamp * 1000, translate("yyyy-MM-dd HH:mm")) 173 } 174 175 function getReplayPlayernames(replay, shorten) 176 { 177 // Extract playernames 178 var playernames = []; 179 for (let i in replay.playerData) 180 { 181 // I've encountered a file where 'null' was added to the playerData array... 182 if (!replay.playerData[i]) 183 { 184 error("Replay " + replay.directory + " has bogus player data!"); 185 continue; 186 } 187 188 var playername = escapeText(replay.playerData[i].Name); 189 190 // TODO: enhancement: colorize playernames like in lobby using colorPlayerName 191 // #3205 moves the function to common/color.js 192 playernames.push(playername); 193 } 194 195 if (!shorten) 196 return playernames; 197 198 playernames = playernames.join(", "); 199 200 // Shorten if too long 201 if (playernames.length > g_maxPlayerlistChars) 202 return playernames.substr(0, g_maxPlayerlistChars) + "..."; 203 else 204 return playernames; 205 } 206 207 function getReplayMapName(replay) 208 { 209 return escapeText(translate(replay.settings.Name)); 210 } 211 212 function getReplayMapSizeText(tiles) 213 { 214 var index = g_mapSizes.tiles.indexOf(tiles); 215 if (index > -1) 216 return g_mapSizes.shortNames[index] 217 else 218 return translateWithContext("map size", "Default"); 219 } 220 221 function getReplayPopCap(replay) 222 { 223 if (replay.settings.PopulationCap == 10000) 224 return translateWithContext("population capacity", "Unlimited"); 225 else 226 return replay.settings.PopulationCap; 227 } 228 229 function getReplayDuration(replay) 230 { 231 return timeToString(replay.duration * 1000); 232 } 233 234 function getReplayTeamText(replay) 235 { 236 var spoiler = Engine.GetGUIObjectByName("showSpoiler").checked; 237 238 // Extract players and civs by team 239 var teams = {}; 240 var teamCount = 0; 241 for (var i in replay.playerData) 242 { 243 var playerData = replay.playerData[i]; 244 245 // I've encountered a file where 'null' was added to the playerData array... 246 if (!playerData) 247 continue; 248 249 var team = playerData.Team; 250 // TODO: enhancement: too few contrast, see #3205 251 var col = playerData.Color ? playerData.Color : g_DefaultPlayerData[parseInt(i)+1].Color; 252 var civ = g_CivData[playerData.Civ]; 253 // TODO: requirement: refactoring with aiconfig.js 254 var aiDiff = [translateWithContext("aiDiff", "Sandbox"), translateWithContext("aiDiff", "Very Easy"), translateWithContext("aiDiff", "Easy"), translateWithContext("aiDiff", "Medium"), translateWithContext("aiDiff", "Hard"), translateWithContext("aiDiff", "Very Hard")]; 255 256 // Create player text 257 var playername = '[color="' + col.r + " " + col.g + " " + col.b + '"]' + escapeText(playerData.Name) + "[/color]"; 258 var playerDetails = translate(civ.Name); 259 if (playerData.AI != "") 260 playerDetails += ", " + sprintf(translateWithContext("replay AI text", "%(difficulty)s %(name)s AI"), { "difficulty": aiDiff[playerData.AIDiff], "name": capitalizeFirstLetter(playerData.AI) }); 261 if (spoiler && replay.defeatedPlayers.indexOf(parseInt(i) + 1) > -1) 262 playerDetails += ", resigned"; 263 264 // Add player text to playerlist 265 var player = playername + escapeText(" (" + playerDetails + ")"); 266 if (teams.hasOwnProperty(team)) 267 { 268 teams[team].push(player); 269 } 270 else 271 { 272 teams[team] = [player]; 273 teamCount++; 274 } 275 } 276 277 // Create player info text sorted by team 278 var teamString = ""; 279 for(var team in teams) 280 { 281 if (teamCount > 1) 282 { 283 if (team == -1) 284 teamString += '[font="sans-bold-14"]No Team:[/font]\n'; 285 else 286 teamString += '[font="sans-bold-14"]Team ' + (parseInt(team) + 1) + "[/font]:\n"; 287 } 288 teamString += teams[team].join("\n") + "\n"; 289 } 290 291 return teamString; 292 } 293 294 function isReplayCompatible(replay) 295 { 296 if (!isReplayCompatible_EngineVersion(replay)) 297 return false; 298 299 // Now check mods 300 if (replay.attribs.mods) 301 var gameMods = replay.attribs.mods; 302 else 303 var gameMods = []; 304 305 if (gameMods.length != g_EngineInfo.mods.length) 306 return false; 307 308 for (var i = 0; i < gameMods.length; ++i) 309 if (gameMods[i] != g_EngineInfo.mods[i]) 310 return false; 311 312 return true; 313 } 314 315 function isReplayCompatible_EngineVersion(replay) 316 { 317 return replay.attribs.hasOwnProperty("engine_version") 318 && replay.attribs.engine_version == g_EngineInfo.engine_version; 319 } 320 321 function initFilters() 322 { 323 initDateFilter(); 324 initMapNameFilter(); 325 initMapSizeFilter(); 326 initPopCapFilter(); 327 initDurationFilter(); 328 } 329 330 function initDateFilter() 331 { 332 var months = ["Any"]; 333 for (var replay of g_Replays) 334 { 335 var month = getDateTimeFilterVal(replay); 336 337 if (months.indexOf(month) == -1) 338 months.push(month); 339 } 340 341 var dateTimeFilter = Engine.GetGUIObjectByName("dateTimeFilter"); 342 dateTimeFilter.list = months; 343 dateTimeFilter.list_data = months; 344 345 if (dateTimeFilter.selected == -1 || dateTimeFilter.selected >= months.length) 346 dateTimeFilter.selected = 0; 347 } 348 349 function getDateTimeFilterVal(replay) 350 { 351 var date = new Date(replay.timestamp * 1000); 352 return date.getFullYear() + "-" + ('0' + (date.getMonth() + 1)).slice(-2) 353 } 354 355 function initMapSizeFilter() 356 { 357 // Get tilecounts actually used by maps 358 var tiles = []; 359 for (let replay of g_Replays) 360 { 361 if (tiles.indexOf(replay.settings.Size) == -1) 362 tiles.push(replay.settings.Size); 363 } 364 tiles.sort(); 365 366 // Add translated names 367 var names = []; 368 for (var size of tiles) 369 names.push(getReplayMapSizeText(size)); 370 371 // Add "Any" 372 names.unshift(translateWithContext("map size", "Any")); 373 tiles.unshift(""); 374 375 // Save values to filter 376 var mapSizeFilter = Engine.GetGUIObjectByName("mapSizeFilter"); 377 mapSizeFilter.list = names; 378 mapSizeFilter.list_data = tiles; 379 380 if (mapSizeFilter.selected == -1 || mapSizeFilter.selected >= tiles.length) 381 mapSizeFilter.selected = 0; 382 } 383 384 function initMapNameFilter() 385 { 386 var mapNames = []; 387 for (var replay of g_Replays) 388 { 389 var mapName = escapeText(replay.settings.Name); 390 391 if (mapNames.indexOf(mapName) == -1) 392 mapNames.push(mapName); 393 } 394 395 mapNames.sort(); 396 mapNames.unshift("Any"); 397 398 var mapNameFilter = Engine.GetGUIObjectByName("mapNameFilter"); 399 mapNameFilter.list = mapNames; 400 mapNameFilter.list_data = mapNames; 401 402 if (mapNameFilter.selected == -1 || mapNameFilter.selected >= mapNames.length) 403 mapNameFilter.selected = 0; 404 } 405 406 function initPopCapFilter() 407 { 408 var popCaps = []; 409 for (var replay of g_Replays) 410 { 411 var popCap = getReplayPopCap(replay); 412 if (popCaps.indexOf(popCap) == -1) 413 popCaps.push(popCap); 414 } 415 popCaps.sort(); 416 417 popCaps.unshift("Any"); 418 var populationFilter = Engine.GetGUIObjectByName("populationFilter"); 419 populationFilter.list = popCaps; 420 populationFilter.list_data = popCaps; 421 422 if (populationFilter.selected == -1 || populationFilter.selected >= popCaps.length) 423 populationFilter.selected = 0; 424 } 425 426 function initDurationFilter() 427 { 428 var data = [-1]; 429 var labels = ["Any"]; 430 431 for (var i in g_DurationFilterMin) 432 { 433 if (i == 0) 434 continue; 435 else if (i == 1) 436 var label = sprintf(translateWithContext("duration filter", "< %(min)s min"), { "min": g_DurationFilterMax[i] }); 437 else if (i == g_DurationFilterMin.length -1) 438 var label = sprintf(translateWithContext("duration filter", "> %(min)s min"), { "min": g_DurationFilterMin[i] }); 439 else 440 var label = sprintf(translateWithContext("duration filter", "%(min1)s - %(min2)s min"), { "min1": g_DurationFilterMin[i], "min2": g_DurationFilterMax[i] }); 441 442 data.push(i); 443 labels.push(label); 444 } 445 446 var durationFilter = Engine.GetGUIObjectByName("durationFilter"); 447 durationFilter.list = labels; 448 durationFilter.list_data = data; 449 450 if (durationFilter.selected == -1 || durationFilter.selected >= data.length) 451 durationFilter.selected = 0; 452 } 453 454 function applyFilters() 455 { 456 // Update the list of replays 457 updateReplayList(); 458 459 // Update info box about the replay currently selected 460 updateReplaySelection(); 461 } 462 463 // Returns true if the replay should not be listed. 464 function filterReplay(replay) 465 { 466 var dateTimeFilter = Engine.GetGUIObjectByName("dateTimeFilter"); 467 var playersFilter = Engine.GetGUIObjectByName("playersFilter"); 468 var mapNameFilter = Engine.GetGUIObjectByName("mapNameFilter"); 469 var mapSizeFilter = Engine.GetGUIObjectByName("mapSizeFilter"); 470 var populationFilter = Engine.GetGUIObjectByName("populationFilter"); 471 var durationFilter = Engine.GetGUIObjectByName("durationFilter"); 472 var compabilityFilter = Engine.GetGUIObjectByName("compabilityFilter"); 473 474 // Check for compability first (most likely to filter) 475 if (compabilityFilter.checked && !isReplayCompatible(replay)) 476 return true; 477 478 // Filter date/time (select a month) 479 if (dateTimeFilter.selected > 0) 480 { 481 let selectedMonth = dateTimeFilter.list_data[dateTimeFilter.selected]; 482 if (getDateTimeFilterVal(replay) != selectedMonth) 483 return true; 484 } 485 486 // Filter selected players 487 let playerText = playersFilter.caption; 488 if (playerText.length) 489 { 490 // Player and botnames can contain spaces 491 // We just check if all words of all players are somewhere in the playerlist 492 playerText = playerText.toLowerCase().split(" "); 493 let replayPlayers = replay.playerData.map(function(player){ return player.Name.toLowerCase() }).join(" "); 494 for (let word of playerText) 495 { 496 if (replayPlayers.indexOf(word) == -1) 497 return true; 498 } 499 } 500 501 // Filter map name 502 if (mapNameFilter.selected > 0) 503 { 504 if (getReplayMapName(replay) != mapNameFilter.list_data[mapNameFilter.selected]) 505 return true; 506 } 507 508 // Filter map size 509 if (mapSizeFilter.selected > 0) 510 { 511 let selectedMapSize = mapSizeFilter.list_data[mapSizeFilter.selected]; 512 if (replay.settings.Size != selectedMapSize) 513 return true; 514 } 515 516 // Filter population capacity 517 if (populationFilter.selected > 0 && 518 getReplayPopCap(replay) != populationFilter.list_data[populationFilter.selected]) 519 { 520 return true; 521 } 522 523 // Filter game duration 524 if (durationFilter.selected > 0) 525 { 526 let minutes = replay.duration / 60; 527 let min = g_DurationFilterMin[durationFilter.selected]; 528 let max = g_DurationFilterMax[durationFilter.selected]; 529 530 if (minutes < min || (max > -1 && minutes > max)) 531 return true; 532 } 533 534 return false; 535 } 536 537 function updateReplaySelection() 538 { 539 var selected = Engine.GetGUIObjectByName("replaySelection").selected; 540 var replaySelected = selected > -1; 541 542 Engine.GetGUIObjectByName("replayInfo").hidden = !replaySelected; 543 Engine.GetGUIObjectByName("replayInfoEmpty").hidden = replaySelected; 544 Engine.GetGUIObjectByName("startReplayButton").enabled = replaySelected; 545 Engine.GetGUIObjectByName("deleteReplayButton").enabled = replaySelected; 546 547 if (!replaySelected) 548 return; 549 550 var replay = g_ReplaysFiltered[selected]; 551 552 // Load map data 553 if (replay.settings.mapType == "random" && replay.attribs.map == "random") 554 var mapData = {"settings": {"Description": translate("A randomly selected map.")}}; 555 else if (replay.settings.mapType == "random" && Engine.FileExists(replay.attribs.map + ".json")) 556 var mapData = Engine.ReadJSONFile(replay.attribs.map + ".json"); 557 else if (Engine.FileExists(replay.attribs.map + ".xml")) 558 var mapData = Engine.LoadMapSettings(replay.attribs.map + ".xml"); 559 else 560 // Warn the player if we can't find the map. 561 warn(sprintf("Map '%(mapName)s' not found locally.", { mapName: replay.attribs.map })); 562 563 // Load map description 564 if (mapData && mapData.settings.Description) 565 var mapDescription = translate(mapData.settings.Description); 566 else 567 var mapDescription = translate("Sorry, no description available."); 568 569 // Load map preview image 570 if (mapData && mapData.settings.Preview) 571 var mapPreview = mapData.settings.Preview; 572 else 573 var mapPreview = "nopreview.png"; 574 575 // Update GUI 576 Engine.GetGUIObjectByName("sgMapName").caption = translate(replay.settings.Name); 577 Engine.GetGUIObjectByName("sgMapSize").caption = getReplayMapSizeText(replay.settings.Size); 578 Engine.GetGUIObjectByName("sgMapType").caption = capitalizeFirstLetter(replay.settings.mapType); 579 Engine.GetGUIObjectByName("sgVictory").caption = capitalizeFirstLetter(replay.settings.GameType); 580 Engine.GetGUIObjectByName("sgNbPlayers").caption = replay.playerData.length; 581 Engine.GetGUIObjectByName("sgPlayersNames").caption = getReplayTeamText(replay); 582 Engine.GetGUIObjectByName("sgMapDescription").caption = mapDescription; 583 Engine.GetGUIObjectByName("sgMapPreview").sprite = "cropped:(0.7812,0.5859)session/icons/mappreview/" + mapPreview; 584 } 585 586 function startReplay() 587 { 588 var selected = Engine.GetGUIObjectByName("replaySelection").selected; 589 if (selected == -1) 590 return; 591 592 var replay = g_ReplaysFiltered[selected]; 593 if (isReplayCompatible(replay)) 594 reallyStartVisualReplay(replay.directory); 595 else 596 displayReplayCompatibilityError(replay); 597 } 598 599 function reallyStartVisualReplay(replayDirectory) 600 { 601 Engine.StartVisualReplay(replayDirectory); 602 Engine.SwitchGuiPage("page_loading.xml", { 603 "attribs": Engine.GetVisualReplayAttributes(replayDirectory), 604 "isNetworked" : false, 605 "playerAssignments": {}, 606 "savedGUIData": "", 607 "isReplay" : true 608 }); 609 } 610 611 function displayReplayCompatibilityError(replay) 612 { 613 if (isReplayCompatible_EngineVersion(replay)) 614 { 615 if (replay.attribs.mods) 616 var gameMods = replay.attribs.mods; 617 else 618 var gameMods = []; 619 620 var errMsg = translate("The replay is compatible with your version of the game, but you don't have the same mods as in the replay.") + "\n"; 621 errMsg += sprintf(translate("Mods enabled in the replay: %(mods)s"), { "mods": gameMods.join(",") }) + "\n"; 622 errMsg += sprintf(translate("Currently enabled mods: %(mods)s"), { "mods": g_EngineInfo.mods.join(",") }); 623 } 624 else 625 { 626 var errMsg = translate("This replay is not compatible with your version of the game!"); 627 } 628 629 var btCaptions = [translate("Ok")]; 630 var btCode = [null]; 631 messageBox(500, 200, errMsg, translate("REPLAY INCOMPATIBLE"), 0, btCaptions, btCode); 632 } 633 634 function deleteReplay() 635 { 636 var selected = Engine.GetGUIObjectByName("replaySelection").selected; 637 if (selected == -1) 638 return; 639 640 // Ask for confirmation 641 var replay = g_ReplaysFiltered[selected]; 642 var btCaptions = [translate("Yes"), translate("No")]; 643 var btCode = [function(){ reallyDeleteReplay(replay.directory); }, null]; 644 messageBox(500, 200, translate("Are you sure to delete this replay permanently?") + "\n" + replay.file, translate("DELETE"), 0, btCaptions, btCode); 645 } 646 647 function deleteReplayWithoutConfirmation() 648 { 649 var selected = Engine.GetGUIObjectByName("replaySelection").selected; 650 if (selected > -1) 651 reallyDeleteReplay(g_ReplaysFiltered[selected].directory); 652 } 653 654 function reallyDeleteReplay(replayDirectory) 655 { 656 if (!Engine.DeleteReplay(replayDirectory)) 657 error(sprintf("Could not delete replay '%(id)s'", { id: replayDirectory })); 658 659 // Refresh replay list 660 init(); 661 } 662 No newline at end of file -
binaries/data/mods/public/gui/replay/replay.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <objects> 4 5 <script file="gui/common/functions_civinfo.js" /> 6 <script file="gui/common/functions_global_object.js" /> 7 <script file="gui/common/functions_utility.js" /> 8 <script file="gui/replay/replay.js" /> 9 10 <object type="image" style="ModernWindow" size="0 0 100% 100%" name="replayWindow"> 11 12 <object style="ModernLabelText" type="text" size="50%-128 0%+4 50%+128 36"> 13 <translatableAttribute id="caption">Replay Games</translatableAttribute> 14 </object> 15 16 <!-- Left Panel: Filters & Replay List --> 17 <object name="leftPanel" size="3% 5% 100%-255 100%-80"> 18 19 <!-- Filters --> 20 <object name="filterPanel" size="0 0 100% 24"> 21 <object name="dateTimeFilter" 22 type="dropdown" 23 style="ModernDropDown" 24 size="5 0 110-10 100%" 25 font="sans-bold-13"> 26 <action on="SelectionChange">applyFilters();</action> 27 </object> 28 <object name="playersFilter" 29 type="input" 30 style="ModernInput" 31 size="110-5 0 110+400-10 100%" 32 font="sans-bold-13"> 33 <action on="Press">applyFilters();</action> 34 <action on="Tab">autoCompleteNick("playersFilter", g_Playernames);</action> 35 </object> 36 <object name="mapNameFilter" 37 type="dropdown" 38 style="ModernDropDown" 39 size="110+400-5 0 110+400+140-10 100%" 40 font="sans-bold-13"> 41 <action on="SelectionChange">applyFilters();</action> 42 </object> 43 <object name="mapSizeFilter" 44 type="dropdown" 45 style="ModernDropDown" 46 size="110+400+140-5 0 110+400+140+80-10 100%" 47 font="sans-bold-13"> 48 <action on="SelectionChange">applyFilters();</action> 49 </object> 50 <object name="populationFilter" 51 type="dropdown" 52 style="ModernDropDown" 53 size="110+400+140+80-5 0 110+400+140+80+80-10 100%" 54 font="sans-bold-13"> 55 <action on="SelectionChange">applyFilters();</action> 56 </object> 57 <object name="durationFilter" 58 type="dropdown" 59 style="ModernDropDown" 60 size="110+400+140+80+80-5 0 110+400+140+80+80+80-10 100%" 61 font="sans-bold-13"> 62 <action on="SelectionChange">applyFilters();</action> 63 </object> 64 <object name="compabilityFilter" 65 type="checkbox" 66 checked="true" 67 style="ModernTickBox" 68 size="110+400+140+80+80+73 4 110+400+140+80+80+70+20 100%" 69 font="sans-bold-13"> 70 <action on="Press">applyFilters();</action> 71 </object> 72 <object type="text" size="110+400+140+80+80+80+10 2 100% 100%" text_align="left" textcolor="white"> 73 <translatableAttribute id="caption">Compatible</translatableAttribute> 74 </object> 75 </object> 76 77 <!-- Replay list --> 78 <object name="replaySelection" size="0 35 100% 100%" style="ModernList" type="olist" sortable="true" default_column="name" sprite_asc="ModernArrowDown" sprite_desc="ModernArrowUp" sprite_not_sorted="ModernNotSorted" font="sans-stroke-13"> 79 <action on="SelectionChange">updateReplaySelection();</action> 80 <action on="SelectionColumnChange">updateReplayListOrderSelection();</action> 81 <!-- Columns --> 82 <!-- 0ad crashes if there is no column with the id "name"! --> 83 <def id="name" color="0 128 128" width="110"> 84 <translatableAttribute id="heading" context="replay">Date / Time</translatableAttribute> 85 </def> 86 <def id="players" color="0 128 128" width="400"> 87 <translatableAttribute id="heading" context="replay">Players</translatableAttribute> 88 </def> 89 <def id="mapName" color="0 128 128" width="140"> 90 <translatableAttribute id="heading" context="replay">Map Name</translatableAttribute> 91 </def> 92 <def id="mapSize" color="0 128 128" width="80"> 93 <translatableAttribute id="heading" context="replay">Size</translatableAttribute> 94 </def> 95 <def id="popCapacity" color="0 128 128" width="80"> 96 <translatableAttribute id="heading" context="replay">Population</translatableAttribute> 97 </def> 98 <def id="duration" color="0 128 128" width="80"> 99 <translatableAttribute id="heading" context="replay">Duration</translatableAttribute> 100 </def> 101 </object> 102 </object> 103 104 <!-- Right Panel: Replay Details --> 105 <object name="rightPanel" size="100%-250 30 100%-20 100%-20" > 106 107 <object name="replayInfoEmpty" size="0 0 100% 100%-60" type="image" sprite="ModernDarkBoxGold" hidden="false"> 108 <object name="logo" size="50%-110 40 50%+110 140" type="image" sprite="logo"/> 109 <object name="subjectBox" type="image" sprite="ModernDarkBoxWhite" size="3% 180 97% 99%"> 110 <object name="subject" size="5 5 100%-5 100%-5" type="text" style="ModernText" text_align="center"/> 111 </object> 112 </object> 113 114 <object name="replayInfo" size="0 0 100% 100%-60" type="image" sprite="ModernDarkBoxGold" hidden="true"> 115 116 <!-- Map Name --> 117 <object name="sgMapName" size="0 5 100% 20" type="text" style="ModernLabelText"/> 118 119 <!-- Map Preview --> 120 <object name="sgMapPreview" size="5 25 100%-5 190" type="image" sprite=""/> 121 122 <object size="5 194 100%-5 195" type="image" sprite="ModernWhiteLine" z="25"/> 123 124 <!-- Map Type --> 125 <object size="5 195 50% 225" type="image" sprite="ModernItemBackShadeLeft"> 126 <object size="0 0 100%-10 100%" type="text" style="ModernLabelText" text_align="right"> 127 <translatableAttribute id="caption">Map Type:</translatableAttribute> 128 </object> 129 </object> 130 <object size="50% 195 100%-5 225" type="image" sprite="ModernItemBackShadeRight"> 131 <object name="sgMapType" size="0 0 100% 100%" type="text" style="ModernLabelText" text_align="left"/> 132 </object> 133 134 <object size="5 224 100%-5 225" type="image" sprite="ModernWhiteLine" z="25"/> 135 136 <!-- Map Size --> 137 <object size="5 225 50% 255" type="image" sprite="ModernItemBackShadeLeft"> 138 <object size="0 0 100%-10 100%" type="text" style="ModernLabelText" text_align="right"> 139 <translatableAttribute id="caption">Map Size:</translatableAttribute> 140 </object> 141 </object> 142 <object size="50% 225 100%-5 255" type="image" sprite="ModernItemBackShadeRight"> 143 <object name="sgMapSize" size="0 0 100% 100%" type="text" style="ModernLabelText" text_align="left"/> 144 </object> 145 146 <object size="5 254 100%-5 255" type="image" sprite="ModernWhiteLine" z="25"/> 147 148 <!-- Victory Condition --> 149 <object size="5 255 50% 285" type="image" sprite="ModernItemBackShadeLeft"> 150 <object size="0 0 100%-10 100%" type="text" style="ModernLabelText" text_align="right"> 151 <translatableAttribute id="caption">Victory:</translatableAttribute> 152 </object> 153 </object> 154 <object size="50% 255 100%-5 285" type="image" sprite="ModernItemBackShadeRight"> 155 <object name="sgVictory" size="0 0 100% 100%" type="text" style="ModernLabelText" text_align="left"/> 156 </object> 157 158 <object size="5 284 100%-5 285" type="image" sprite="ModernWhiteLine" z="25"/> 159 160 <!-- Map Description --> 161 <object type="image" sprite="ModernDarkBoxWhite" size="3% 290 97% 70%"> 162 <object name="sgMapDescription" size="0 0 100% 100%" type="text" style="ModernText" font="sans-12"/> 163 </object> 164 165 <object type="image" sprite="ModernDarkBoxWhite" size="3% 70%+5 97% 100%-30"> 166 <!-- Number of Players --> 167 <object size="0% 3% 57% 12%" type="text" style="ModernRightLabelText"> 168 <translatableAttribute id="caption">Players:</translatableAttribute> 169 </object> 170 <object name="sgNbPlayers" size="58% 3% 70% 12%" type="text" style="ModernLeftLabelText" text_align="left"/> 171 172 <!-- Player Names --> 173 <object name="sgPlayersNames" size="0 15% 100% 100%" type="text" style="MapPlayerList"/> 174 </object> 175 176 <object name="showSpoiler" 177 type="checkbox" 178 checked="false" 179 style="ModernTickBox" 180 size="10 100%-27 30 100%" 181 font="sans-bold-13"> 182 <action on="Press">updateReplaySelection();</action> 183 </object> 184 <object type="text" size="30 100%-28 100% 100%" text_align="left" textcolor="white"> 185 <translatableAttribute id="caption">Spoiler</translatableAttribute> 186 </object> 187 188 </object> 189 </object> 190 191 <!-- Bottom Panel: Buttons. --> 192 <object name="bottomPanel" size="25 100%-55 100%-5 100%-25" > 193 194 <object type="button" style="StoneButton" size="0%+25 0 17%+25 100%"> 195 <translatableAttribute id="caption">Main Menu</translatableAttribute> 196 <action on="Press"> 197 Engine.SwitchGuiPage("page_pregame.xml"); 198 </action> 199 </object> 200 201 <object name="deleteReplayButton" type="button" style="StoneButton" size="65%-50 0 82%-50 100%" hotkey="session.savedgames.delete"> 202 <translatableAttribute id="caption">Delete</translatableAttribute> 203 <action on="Press"> 204 if (!this.enabled) 205 return; 206 if (Engine.HotkeyIsPressed("session.savedgames.noConfirmation")) 207 deleteReplayWithoutConfirmation(); 208 else 209 deleteReplay(); 210 </action> 211 </object> 212 213 <object name="startReplayButton" type="button" style="StoneButton" size="83%-25 0 100%-25 100%"> 214 <translatableAttribute id="caption">Start Replay</translatableAttribute> 215 <action on="Press"> 216 startReplay(); 217 </action> 218 </object> 219 220 </object> 221 </object> 222 </objects> 223 No newline at end of file -
binaries/data/mods/public/gui/replay/styles.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <styles> 4 <style name="MapPlayerList" 5 buffer_zone="8" 6 font="sans-14" 7 scrollbar="true" 8 scrollbar_style="ModernScrollBar" 9 scroll_bottom="true" 10 textcolor="white" 11 text_align="left" 12 text_valign="top" 13 /> 14 </styles> -
binaries/data/mods/public/gui/session/session.js
5 5 var g_IsController; 6 6 // Match ID for tracking 7 7 var g_MatchID; 8 8 // Is this user an observer? 9 9 var g_IsObserver = false; 10 var g_IsReplay = false; 10 11 11 12 // Cache the basic player data (name, civ, color) 12 13 var g_Players = []; 13 14 // Cache the useful civ data 14 15 var g_CivData = {}; … … 149 150 { 150 151 if (initData) 151 152 { 152 153 g_IsNetworked = initData.isNetworked; // Set network mode 153 154 g_IsController = initData.isController; // Set controller mode 155 g_IsReplay = initData.isReplay; // Set replay mode 154 156 g_PlayerAssignments = initData.playerAssignments; 155 157 g_MatchID = initData.attribs.matchID; 156 158 157 159 // Cache the player data 158 160 // (This may be updated at runtime by handleNetMessage) … … 352 354 Engine.SwitchGuiPage("page_summary.xml", { 353 355 "gameResult" : gameResult, 354 356 "timeElapsed" : extendedSimState.timeElapsed, 355 357 "playerStates": extendedSimState.players, 356 358 "players": g_Players, 357 "mapSettings": mapSettings 359 "mapSettings": mapSettings, 360 "isReplay" : g_IsReplay 358 361 }); 359 362 } 360 363 361 364 // Return some data that we'll use when hotloading this file after changes 362 365 function getHotloadData() -
binaries/data/mods/public/gui/summary/summary.js
28 28 const INCOME_COLOR = '[color="201 255 200"]'; 29 29 const OUTCOME_COLOR = '[color="255 213 213"]'; 30 30 31 31 const DEFAULT_DECIMAL = "0.00"; 32 32 const INFINITE_SYMBOL = "\u221E"; 33 var g_IsReplay = false; 33 34 // Load data 34 35 var g_CivData = loadCivData(); 35 36 var g_Teams = [ ]; 36 37 // TODO set g_MaxPlayers as playerCounters.length 37 38 var g_MaxPlayers = 0; … … 132 133 133 134 function init(data) 134 135 { 135 136 updateObjectPlayerPosition(); 136 137 g_GameData = data; 137 138 g_IsReplay = data.isReplay; 138 139 // Map 139 140 var mapDisplayType = translate("Scenario"); 140 141 141 142 Engine.GetGUIObjectByName("timeElapsed").caption = sprintf(translate("Game time elapsed: %(time)s"), { time: timeToString(data.timeElapsed) }); 142 143 … … 165 166 g_MaxPlayers = data.playerStates.length - 1; 166 167 167 168 if (data.mapSettings.LockTeams) // teams ARE locked 168 169 { 169 170 // count teams 170 for (var t = 0; t < g_MaxPlayers; ++t)171 for (var t = 0; t < g_MaxPlayers; ++t) 171 172 { 172 173 if (!g_Teams[data.playerStates[t+1].team]) 173 174 { 174 175 g_Teams[data.playerStates[t+1].team] = 1; 175 176 continue; … … 184 185 g_Teams = false; 185 186 186 187 // Erase teams data if teams are not displayed 187 188 if (!g_Teams) 188 189 { 189 for (var p = 0; p < g_MaxPlayers; ++p)190 for (var p = 0; p < g_MaxPlayers; ++p) 190 191 data.playerStates[p+1].team = -1; 191 192 } 192 193 193 194 g_WithoutTeam = g_MaxPlayers; 194 195 if (g_Teams) -
binaries/data/mods/public/gui/summary/summary.xml
155 155 </object> 156 156 157 157 <object type="button" style="ModernButtonRed" size="100%-160 100%-48 100%-20 100%-20"> 158 158 <translatableAttribute id="caption">Continue</translatableAttribute> 159 159 <action on="Press"><![CDATA[ 160 if ( !Engine.HasXmppClient())160 if (Engine.HasXmppClient()) 161 161 { 162 Engine.SwitchGuiPage("page_pregame.xml"); 162 Engine.LobbySetPlayerPresence("available"); 163 Engine.SwitchGuiPage("page_lobby.xml"); 164 } 165 else if (g_IsReplay) 166 { 167 Engine.SwitchGuiPage("page_replay.xml"); 163 168 } 164 169 else 165 170 { 166 Engine.LobbySetPlayerPresence("available"); 167 Engine.SwitchGuiPage("page_lobby.xml"); 171 Engine.SwitchGuiPage("page_pregame.xml"); 168 172 } 169 173 ]]> 170 174 </action> 171 175 </object> 172 176 </object> -
binaries/data/mods/public/simulation/data/game_speeds.json
31 31 "Speed": 1.5 32 32 }, 33 33 { 34 34 "Name": "Insane (2x)", 35 35 "Speed": 2.0 36 }, 37 { 38 "Name": "Fast forward (5x)", 39 "Speed": 5.0 40 }, 41 { 42 "Name": "Faster forward (10x)", 43 "Speed": 10.0 44 }, 45 { 46 "Name": "Very fast forward (20x)", 47 "Speed": 20.0 36 48 } 37 49 ] 38 50 } -
source/gui/scripting/ScriptFunctions.cpp
48 48 #include "ps/Globals.h" // g_frequencyFilter 49 49 #include "ps/Hotkey.h" 50 50 #include "ps/ProfileViewer.h" 51 51 #include "ps/Pyrogenesis.h" 52 52 #include "ps/SavedGame.h" 53 #include "ps/VisualReplay.h" 53 54 #include "ps/UserReport.h" 54 55 #include "ps/World.h" 55 56 #include "ps/scripting/JSInterface_ConfigDB.h" 56 57 #include "ps/scripting/JSInterface_Console.h" 57 58 #include "ps/scripting/JSInterface_Mod.h" … … 281 282 shared_ptr<ScriptInterface::StructuredClone> GUIMetadataClone = pCxPrivate->pScriptInterface->WriteStructuredClone(GUIMetadata); 282 283 if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), GUIMetadataClone, g_Game->GetPlayerID()) < 0) 283 284 LOGERROR("Failed to save game"); 284 285 } 285 286 287 JS::Value StartVisualReplay(ScriptInterface::CxPrivate* pCxPrivate, std::wstring directoryName) 288 { 289 JSContext* cxGui = pCxPrivate->pScriptInterface->GetContext(); 290 JSAutoRequest rq(cxGui); 291 JS::RootedValue guiContextMetadata(cxGui); 292 293 ENSURE(!g_NetServer); 294 ENSURE(!g_NetClient); 295 ENSURE(!g_Game); 296 297 CStrW replayFilePath = OsPath(VisualReplay::GetDirectoryName() / directoryName / L"commands.txt").string(); 298 std::string replayFile( replayFilePath.begin(), replayFilePath.end() ); 299 300 if (FileExists(OsPath(replayFile))) 301 { 302 g_Game = new CGame(false, false); 303 g_Game->StartReplay(replayFile); 304 } 305 306 return guiContextMetadata; 307 } 308 309 JS::Value GetVisualReplayAttributes(ScriptInterface::CxPrivate* pCxPrivate, std::wstring directoryName) 310 { 311 CStrW replayFilePath = OsPath(VisualReplay::GetDirectoryName() / directoryName / "commands.txt").string(); 312 std::string replayFile( replayFilePath.begin(), replayFilePath.end() ); 313 314 if (!FileExists(OsPath(replayFile))) 315 return {}; 316 317 std::istream* replayStream = new std::ifstream(replayFile.c_str()); 318 std::string type, line; 319 ENSURE((*replayStream >> type).good() && type == "start"); 320 321 std::getline(*replayStream, line); 322 JS::RootedValue attribs(pCxPrivate->pScriptInterface->GetContext()); 323 pCxPrivate->pScriptInterface->ParseJSON(line, &attribs); 324 delete replayStream; 325 return attribs; 326 } 327 286 328 void SetNetworkGameAttributes(ScriptInterface::CxPrivate* pCxPrivate, JS::HandleValue attribs1) 287 329 { 288 330 ENSURE(g_NetServer); 289 331 //TODO: This is a workaround because we need to pass a MutableHandle to a JSAPI functions somewhere 290 332 // (with no obvious reason). … … 415 457 bool DeleteSavedGame(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring name) 416 458 { 417 459 return SavedGames::DeleteSavedGame(name); 418 460 } 419 461 462 JS::Value GetReplays(ScriptInterface::CxPrivate* pCxPrivate) 463 { 464 return VisualReplay::GetReplays(*(pCxPrivate->pScriptInterface)); 465 } 466 467 bool DeleteReplay(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::wstring replayFile) 468 { 469 return VisualReplay::DeleteReplay(replayFile); 470 } 471 420 472 void OpenURL(ScriptInterface::CxPrivate* UNUSED(pCxPrivate), std::string url) 421 473 { 422 474 sys_open_url(url); 423 475 } 424 476 … … 974 1026 scriptInterface.RegisterFunction<void, std::wstring, std::wstring, JS::HandleValue, &SaveGame>("SaveGame"); 975 1027 scriptInterface.RegisterFunction<void, std::wstring, std::wstring, JS::HandleValue, &SaveGamePrefix>("SaveGamePrefix"); 976 1028 scriptInterface.RegisterFunction<void, &QuickSave>("QuickSave"); 977 1029 scriptInterface.RegisterFunction<void, &QuickLoad>("QuickLoad"); 978 1030 1031 // Visual replay 1032 scriptInterface.RegisterFunction<JS::Value, &GetReplays>("GetReplays"); 1033 scriptInterface.RegisterFunction<bool, std::wstring, &DeleteReplay>("DeleteReplay"); 1034 scriptInterface.RegisterFunction<JS::Value, std::wstring, &StartVisualReplay>("StartVisualReplay"); 1035 scriptInterface.RegisterFunction<JS::Value, std::wstring, &GetVisualReplayAttributes>("GetVisualReplayAttributes"); 1036 979 1037 // Misc functions 980 1038 scriptInterface.RegisterFunction<std::wstring, std::wstring, &SetCursor>("SetCursor"); 981 1039 scriptInterface.RegisterFunction<int, &GetPlayerID>("GetPlayerID"); 982 1040 scriptInterface.RegisterFunction<void, int, &SetPlayerID>("SetPlayerID"); 983 1041 scriptInterface.RegisterFunction<void, std::string, &OpenURL>("OpenURL"); -
source/lobby/XmppClient.cpp
22 22 #include "glooxwrapper/glooxwrapper.h" 23 23 #include "i18n/L10n.h" 24 24 #include "lib/utf8.h" 25 25 #include "ps/CLogger.h" 26 26 #include "ps/ConfigDB.h" 27 #include "ps/EngineVersion.h" 27 28 #include "scriptinterface/ScriptInterface.h" 28 29 29 30 //debug 30 31 #if 1 31 32 #define DbgXMPP(x) … … 95 96 const int mechs = gloox::SaslMechAll ^ gloox::SaslMechPlain; 96 97 m_client->setSASLMechanisms(mechs); 97 98 98 99 m_client->registerConnectionListener(this); 99 100 m_client->setPresence(gloox::Presence::Available, -1); 100 m_client->disco()->setVersion("Pyrogenesis", "0.0.19");101 m_client->disco()->setVersion("Pyrogenesis", utf8_from_wstring(engine_version)); 101 102 m_client->disco()->setIdentity("client", "bot"); 102 103 m_client->setCompression(false); 103 104 104 105 m_client->registerStanzaExtension(new GameListQuery()); 105 106 m_client->registerIqHandler(this, EXTGAMELISTQUERY); -
source/ps/EngineVersion.h
1 const wchar_t engine_version[] = L"0.0.19"; -
source/ps/Game.cpp
134 134 if (type == "turn") 135 135 { 136 136 u32 turn = 0; 137 137 u32 turnLength = 0; 138 138 *m_ReplayStream >> turn >> turnLength; 139 140 if (turn == 0 && turn != currentTurn) 141 LOGERROR("Looks like you tried to replay a commands.txt file of a rejoined client.\n"); 142 139 143 ENSURE(turn == currentTurn); 144 140 145 replayTurnMgr->StoreReplayTurnLength(currentTurn, turnLength); 141 146 } 142 147 else if (type == "cmd") 143 148 { 144 149 player_id_t player; … … 162 167 else 163 168 { 164 169 CancelLoad(L"Failed to load replay data (unrecognized content)"); 165 170 } 166 171 } 172 m_ReplayStream->close(); 167 173 m_FinalReplayTurn = currentTurn; 168 174 replayTurnMgr->StoreFinalReplayTurn(currentTurn); 169 175 return 0; 170 176 } 171 177 … … 173 179 { 174 180 m_IsReplay = true; 175 181 ScriptInterface& scriptInterface = m_Simulation2->GetScriptInterface(); 176 182 177 183 SetTurnManager(new CNetReplayTurnManager(*m_Simulation2, GetReplayLogger())); 184 SetPlayerID(-1); 178 185 179 186 m_ReplayPath = replayPath; 180 187 m_ReplayStream = new std::ifstream(m_ReplayPath.c_str()); 181 188 182 189 std::string type; -
source/ps/Game.h
176 176 bool m_IsSavedGame; // true if loading a saved game; false for a new game 177 177 178 178 int LoadReplayData(); 179 179 std::string m_ReplayPath; 180 180 bool m_IsReplay; 181 std::i stream* m_ReplayStream;181 std::ifstream* m_ReplayStream; 182 182 u32 m_FinalReplayTurn; 183 183 }; 184 184 185 185 extern CGame *g_Game; 186 186 -
source/ps/GameSetup/GameSetup.cpp
879 879 srand(time(NULL)); // NOTE: this rand should *not* be used for simulation! 880 880 } 881 881 882 882 bool Autostart(const CmdLineArgs& args); 883 883 884 // Returns true if and only if the user has intended to replay a file 885 bool VisualReplay(const std::string replayFile); 884 bool StartVisualReplay(const std::string replayFile); 886 885 887 886 bool Init(const CmdLineArgs& args, int flags) 888 887 { 889 888 h_mgr_init(); 890 889 … … 1078 1077 if (VfsDirectoryExists(L"maps/")) 1079 1078 CXeromyces::AddValidator(g_VFS, "map", "maps/scenario.rng"); 1080 1079 1081 1080 try 1082 1081 { 1083 if (! VisualReplay(args.Get("replay-visual")) && !Autostart(args))1082 if (!StartVisualReplay(args.Get("replay-visual")) && !Autostart(args)) 1084 1083 { 1085 1084 const bool setup_gui = ((flags & INIT_NO_GUI) == 0); 1086 1085 // We only want to display the splash screen at startup 1087 1086 shared_ptr<ScriptInterface> scriptInterface = g_GUI->GetScriptInterface(); 1088 1087 JSContext* cx = scriptInterface->GetContext(); … … 1475 1474 } 1476 1475 1477 1476 return true; 1478 1477 } 1479 1478 1480 bool VisualReplay(const std::string replayFile)1479 bool StartVisualReplay(const std::string replayFile) 1481 1480 { 1482 1481 if (!FileExists(OsPath(replayFile))) 1483 1482 return false; 1484 1483 1485 1484 g_Game = new CGame(false, false); 1486 g_Game->SetPlayerID(-1);1487 1485 g_Game->StartReplay(replayFile); 1488 1486 1489 1487 // TODO: Non progressive load can fail - need a decent way to handle this 1490 1488 LDR_NonprogressiveLoad(); 1491 1489 -
source/ps/Pyrogenesis.cpp
1 /* Copyright (C) 20 09Wildfire Games.1 /* Copyright (C) 2015 Wildfire Games. 2 2 * This file is part of 0 A.D. 3 3 * 4 4 * 0 A.D. is free software: you can redistribute it and/or modify 5 5 * it under the terms of the GNU General Public License as published by 6 6 * the Free Software Foundation, either version 2 of the License, or … … 19 19 20 20 #include <cstdio> 21 21 22 22 #include "Pyrogenesis.h" 23 23 24 #include "ps/EngineVersion.h" 24 25 #include "lib/sysdep/sysdep.h" 25 26 #include "lib/svn_revision.h" 26 27 27 28 static const wchar_t* translate_no_mem = L"(no mem)"; 28 29 … … 71 72 72 73 // for user convenience, bundle all logs into this file: 73 74 void psBundleLogs(FILE* f) 74 75 { 75 76 fwprintf(f, L"SVN Revision: %ls\n\n", svn_revision); 77 fwprintf(f, L"Engine Version: %ls\n\n", engine_version); 76 78 77 79 fwprintf(f, L"System info:\n\n"); 78 80 OsPath path1 = psLogDir()/"system_info.txt"; 79 81 AppendAsciiFile(f, path1); 80 82 fwprintf(f, L"\n\n====================================\n\n"); -
source/ps/Replay.cpp
22 22 #include "graphics/TerrainTextureManager.h" 23 23 #include "lib/timer.h" 24 24 #include "lib/file/file_system.h" 25 25 #include "lib/res/h_mgr.h" 26 26 #include "lib/tex/tex.h" 27 #include "ps/EngineVersion.h" 27 28 #include "ps/Game.h" 28 29 #include "ps/Loader.h" 29 30 #include "ps/Profile.h" 31 #include "ps/Mod.h" 30 32 #include "ps/ProfileViewer.h" 31 33 #include "scriptinterface/ScriptInterface.h" 32 34 #include "scriptinterface/ScriptStats.h" 33 35 #include "simulation2/Simulation2.h" 34 36 #include "simulation2/helpers/SimulationCommand.h" … … 52 54 } 53 55 54 56 CReplayLogger::CReplayLogger(ScriptInterface& scriptInterface) : 55 57 m_ScriptInterface(scriptInterface) 56 58 { 59 m_Stream = NULL; 60 } 61 62 CReplayLogger::~CReplayLogger() 63 { 64 delete m_Stream; 65 } 66 67 void CReplayLogger::StartGame(JS::MutableHandleValue attribs) 68 { 57 69 // Construct the directory name based on the PID, to be relatively unique. 58 70 // Append "-1", "-2" etc if we run multiple matches in a single session, 59 71 // to avoid accidentally overwriting earlier logs. 60 72 61 73 std::wstringstream name; … … 65 77 if (++run) 66 78 name << "-" << run; 67 79 68 80 OsPath path = psLogDir() / L"sim_log" / name.str() / L"commands.txt"; 69 81 CreateDirectories(path.Parent(), 0700); 70 m_Stream = new std::ofstream(OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc);71 }72 82 73 CReplayLogger::~CReplayLogger() 74 { 75 delete m_Stream;76 } 83 // Add timestamp and engine version to game attributes 84 m_ScriptInterface.SetProperty(attribs, "timestamp", std::time(0)); 85 m_ScriptInterface.SetProperty(attribs, "engine_version", utf8_from_wstring(engine_version)); 86 m_ScriptInterface.SetProperty(attribs, "mods", g_modsLoaded); 77 87 78 void CReplayLogger::StartGame(JS::MutableHandleValue attribs) 79 { 88 m_Stream = new std::ofstream(OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc); 80 89 *m_Stream << "start " << m_ScriptInterface.StringifyJSON(attribs, false) << "\n"; 81 90 } 82 91 83 92 void CReplayLogger::Turn(u32 n, u32 turnLength, std::vector<SimulationCommand>& commands) 84 93 { … … 157 166 JSContext* cx = g_Game->GetSimulation2()->GetScriptInterface().GetContext(); 158 167 JSAutoRequest rq(cx); 159 168 std::string type; 160 169 while ((*m_Stream >> type).good()) 161 170 { 162 // if (turn >= 1400) break;163 164 171 if (type == "start") 165 172 { 166 173 std::string line; 167 174 std::getline(*m_Stream, line); 168 175 JS::RootedValue attribs(cx); … … 198 205 std::string replayHash; 199 206 *m_Stream >> replayHash; 200 207 201 208 bool quick = (type == "hash-quick"); 202 209 203 // if (turn >= 1300)204 // if (turn >= 0)205 210 if (turn % 100 == 0) 206 211 { 207 212 std::string hash; 208 213 bool ok = g_Game->GetSimulation2()->ComputeStateHash(hash, quick); 209 214 ENSURE(ok); … … 224 229 225 230 g_Game->GetSimulation2()->Update(turnLength, commands); 226 231 commands.clear(); 227 232 } 228 233 229 // std::string hash;230 // bool ok = g_Game->GetSimulation2()->ComputeStateHash(hash, true);231 // ENSURE(ok);232 // debug_printf("%s\n", Hexify(hash).c_str());233 234 234 g_Profiler.Frame(); 235 235 236 // if (turn % 1000 == 0)237 // JS_GC(g_Game->GetSimulation2()->GetScriptInterface().GetContext());238 239 236 if (turn % 20 == 0) 240 237 g_ProfileViewer.SaveToFile(); 241 238 } 242 239 else 243 240 { 244 241 debug_printf("Unrecognised replay token %s\n", type.c_str()); 245 242 } 246 243 } 247 244 } 248 245 m_Stream->close(); 249 246 g_Profiler2.SaveToFile(); 250 247 251 248 std::string hash; 252 249 bool ok = g_Game->GetSimulation2()->ComputeStateHash(hash, false); 253 250 ENSURE(ok); -
source/ps/Replay.h
90 90 91 91 void Load(const std::string& path); 92 92 void Replay(bool serializationtest, bool ooslog); 93 93 94 94 private: 95 std::i stream* m_Stream;95 std::ifstream* m_Stream; 96 96 }; 97 97 98 98 #endif // INCLUDED_REPLAY -
source/ps/SavedGame.cpp
1 /* Copyright (C) 201 4Wildfire Games.1 /* Copyright (C) 2015 Wildfire Games. 2 2 * This file is part of 0 A.D. 3 3 * 4 4 * 0 A.D. is free software: you can redistribute it and/or modify 5 5 * it under the terms of the GNU General Public License as published by 6 6 * the Free Software Foundation, either version 2 of the License, or … … 24 24 #include "lib/allocators/shared_ptr.h" 25 25 #include "lib/file/archive/archive_zip.h" 26 26 #include "i18n/L10n.h" 27 27 #include "lib/utf8.h" 28 28 #include "ps/CLogger.h" 29 #include "ps/EngineVersion.h" 29 30 #include "ps/Filesystem.h" 30 31 #include "ps/Game.h" 31 32 #include "ps/Mod.h" 32 33 #include "scriptinterface/ScriptInterface.h" 33 34 #include "simulation2/Simulation2.h" … … 84 85 JS::RootedValue metadata(cx); 85 86 JS::RootedValue initAttributes(cx, simulation.GetInitAttributes()); 86 87 simulation.GetScriptInterface().Eval("({})", &metadata); 87 88 simulation.GetScriptInterface().SetProperty(metadata, "version_major", SAVED_GAME_VERSION_MAJOR); 88 89 simulation.GetScriptInterface().SetProperty(metadata, "version_minor", SAVED_GAME_VERSION_MINOR); 90 simulation.GetScriptInterface().SetProperty(metadata, "engine_version", utf8_from_wstring(engine_version)); 91 89 92 simulation.GetScriptInterface().SetProperty(metadata, "mods", g_modsLoaded); 90 93 simulation.GetScriptInterface().SetProperty(metadata, "time", (double)now); 91 94 simulation.GetScriptInterface().SetProperty(metadata, "player", playerID); 92 95 simulation.GetScriptInterface().SetProperty(metadata, "initAttributes", initAttributes); 93 96 … … 296 299 JSContext* cx = scriptInterface.GetContext(); 297 300 JSAutoRequest rq(cx); 298 301 299 302 JS::RootedValue metainfo(cx); 300 303 scriptInterface.Eval("({})", &metainfo); 301 scriptInterface.SetProperty(metainfo, "version_major", SAVED_GAME_VERSION_MAJOR); 302 scriptInterface.SetProperty(metainfo, "version_minor", SAVED_GAME_VERSION_MINOR); 303 scriptInterface.SetProperty(metainfo, "mods" , g_modsLoaded); 304 scriptInterface.SetProperty(metainfo, "version_major", SAVED_GAME_VERSION_MAJOR); 305 scriptInterface.SetProperty(metainfo, "version_minor", SAVED_GAME_VERSION_MINOR); 306 scriptInterface.SetProperty(metainfo, "engine_version", utf8_from_wstring(engine_version)); 307 308 scriptInterface.SetProperty(metainfo, "mods", g_modsLoaded); 304 309 return metainfo; 305 310 } 306 311 -
source/ps/VisualReplay.cpp
1 /* Copyright (C) 2015 Wildfire Games. 2 * This file is part of 0 A.D. 3 * 4 * 0 A.D. is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 2 of the License, or 7 * (at your option) any later version. 8 * 9 * 0 A.D. is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 #include "precompiled.h" 19 20 #include "VisualReplay.h" 21 22 #include "graphics/GameView.h" 23 #include "gui/GUIManager.h" 24 #include "lib/allocators/shared_ptr.h" 25 #include "lib/utf8.h" 26 #include "ps/CLogger.h" 27 #include "ps/EngineVersion.h" 28 #include "ps/Filesystem.h" 29 #include "ps/Game.h" 30 #include "scriptinterface/ScriptInterface.h" 31 32 OsPath VisualReplay::GetDirectoryName() 33 { 34 return OsPath(psLogDir() / L"sim_log"); 35 } 36 37 JS::Value VisualReplay::GetReplays(ScriptInterface& scriptInterface) 38 { 39 // TODO: enhancement: load from cache 40 41 TIMER(L"GetReplays"); 42 JSContext* cx = scriptInterface.GetContext(); 43 JSAutoRequest rq(cx); 44 45 u32 i = 0; 46 DirectoryNames directories; 47 JS::RootedObject replays(cx, JS_NewArrayObject(cx, 0)); 48 GetDirectoryEntries(GetDirectoryName(), NULL, &directories); 49 for (auto& directory : directories) 50 { 51 JS::RootedValue replayData(cx, LoadReplayData(scriptInterface, directory)); 52 if (!replayData.isNull()) 53 JS_SetElement(cx, replays, i++, replayData); 54 } 55 return JS::ObjectValue(*replays); 56 } 57 58 // Works similar to CGame::LoadReplayData() 59 // Extracts metadata from file header, loads commands and computes duration of the game 60 JS::Value VisualReplay::LoadReplayData(ScriptInterface& scriptInterface, OsPath directory) 61 { 62 OsPath replayFile(GetDirectoryName() / directory / L"commands.txt"); 63 64 if (!FileExists(replayFile)) 65 return JSVAL_NULL; 66 67 // Get fileinfo (size, timestamp) 68 CFileInfo fileInfo; 69 GetFileInfo(replayFile, &fileInfo); 70 u64 fileTime = (u64)fileInfo.MTime() & ~1; // skip lowest bit, since zip and FAT don't preserve it (according to CCacheLoader::LooseCachePath) 71 u64 fileSize = (u64)fileInfo.Size(); 72 73 if (fileSize == 0) 74 return JSVAL_NULL; 75 76 // Open file 77 std::wstring filenameW = replayFile.string(); 78 std::string filename( filenameW.begin(), filenameW.end() ); 79 std::ifstream* replayStream = new std::ifstream(filename.c_str()); 80 81 // File must begin with "start" 82 std::string type; 83 ENSURE((*replayStream >> type).good() && type == "start"); 84 85 // Parse header 86 std::string header; 87 std::getline(*replayStream, header); 88 JSContext* cx = scriptInterface.GetContext(); 89 JSAutoRequest rq(cx); 90 JS::RootedValue attribs(cx); 91 if (!scriptInterface.ParseJSON(header, &attribs)) 92 return JSVAL_NULL; 93 94 // Parse commands & turns 95 u32 currentTurn = 0; 96 u32 currentMinute = 0; 97 u64 duration = 0; 98 std::vector<player_id_t> defeatedPlayers; 99 std::map<player_id_t, u16> currentCommandCount; 100 std::map<player_id_t, u16> commandsPerMinute; 101 while ((*replayStream >> type).good()) 102 { 103 if (type == "turn") 104 { 105 // Store turn & turn length 106 u32 turn = 0; 107 u32 turnLength = 0; 108 *replayStream >> turn >> turnLength; 109 if (turn != currentTurn) // Happens for replays of rejoined clients 110 return JSVAL_NULL; 111 112 // Compute game duration 113 duration += turnLength; 114 115 // Compute commands per minute 116 u32 min = duration / 1000 / 60; 117 if (min > currentMinute) 118 { 119 //commandsPerMinute[player][currentMinute] = currentCommandCount[player]; 120 currentMinute = min; 121 } 122 } 123 else if (type == "cmd") 124 { 125 // Extract player id 126 player_id_t player; 127 *replayStream >> player; 128 129 // Increase command count 130 if (currentCommandCount.find(player) == currentCommandCount.end()) 131 currentCommandCount[player] = 1; 132 else 133 currentCommandCount[player]++; 134 135 // Store command 136 std::string command; 137 std::getline(*replayStream, command); 138 139 // Parse command 140 JS::RootedValue commandData(scriptInterface.GetContext()); 141 std::wstring commandType; 142 if (!scriptInterface.ParseJSON(command, &commandData)) 143 { 144 LOGERROR("Corrupted replay command '%s' in file '%s'", command, filename.c_str()); 145 return JSVAL_NULL; 146 } 147 scriptInterface.GetProperty(commandData, "type", commandType); 148 149 // Save defeated players {"type":"defeat-player","playerId":2} 150 if (commandType == L"defeat-player") 151 { 152 player_id_t defeatedPlayer; 153 scriptInterface.GetProperty(commandData, "playerId", defeatedPlayer); 154 defeatedPlayers.push_back(defeatedPlayer); 155 } 156 } 157 else if (type == "hash" || type == "hash-quick") 158 { 159 // Skip hash values 160 std::string replayHash; 161 *replayStream >> replayHash; 162 } 163 else if (type == "end") 164 { 165 currentTurn++; 166 } 167 else 168 { 169 LOGERROR("Unrecognized replay data '%s' in file %s", type, filename.c_str()); 170 } 171 } 172 replayStream->close(); 173 174 duration = duration / 1000; 175 if (duration < 5) // Don't list too short replays 176 return JSVAL_NULL; 177 178 // finalReplayTurn = currentTurn; 179 // TODO: compute average turn time, if turn length varies 180 181 JS::RootedValue replayData(cx); 182 scriptInterface.Eval("({})", &replayData); 183 scriptInterface.SetProperty(replayData, "file", replayFile); 184 scriptInterface.SetProperty(replayData, "directory", directory); 185 scriptInterface.SetProperty(replayData, "filemod_timestamp", fileTime); 186 scriptInterface.SetProperty(replayData, "attribs", attribs); 187 scriptInterface.SetProperty(replayData, "duration", duration); 188 scriptInterface.SetProperty(replayData, "defeatedPlayers", defeatedPlayers); 189 return replayData; 190 } 191 192 bool VisualReplay::DeleteReplay(const std::wstring replayDirectory) 193 { 194 if (replayDirectory == L"") 195 return false; 196 197 const OsPath directory = OsPath(GetDirectoryName() / replayDirectory); 198 return DirectoryExists(directory) && DeleteDirectory(directory) == INFO::OK; 199 } -
source/ps/VisualReplay.h
1 /* Copyright (C) 2015 Wildfire Games. 2 * This file is part of 0 A.D. 3 * 4 * 0 A.D. is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 2 of the License, or 7 * (at your option) any later version. 8 * 9 * 0 A.D. is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 #ifndef INCLUDED_REPlAY 19 #define INCLUDED_REPlAY 20 21 #include "scriptinterface/ScriptInterface.h" 22 class CSimulation2; 23 class CGUIManager; 24 25 /** 26 * Contains functions for visually replaying past games. 27 */ 28 29 namespace VisualReplay 30 { 31 32 /** 33 * Start replaying the given commands.txt. 34 * 35 * @param name filename of the commands.txt file (including path) 36 * @param scriptInterface 37 * @param[out] savedState serialized simulation state stored as string of bytes, 38 * loaded from simulation.dat inside the archive. 39 * @return INFO::OK if successfully loaded, else an error Status 40 */ 41 Status Load(const std::wstring& name, ScriptInterface& scriptInterface, std::string& savedState); 42 43 /** 44 * Returns the path to the sim-log directory (that contains the directories with the replay files. 45 * 46 * @param scriptInterface the ScriptInterface in which to create the return data. 47 * @return OsPath with an absolte file path 48 */ 49 OsPath GetDirectoryName(); 50 51 /** 52 * Get a list of replays (filenames and timestamps [later more information like playernames]) for GUI script usage 53 * 54 * @param scriptInterface the ScriptInterface in which to create the return data. 55 * @return array of objects containing saved game data 56 */ 57 JS::Value GetReplays(ScriptInterface& scriptInterface); 58 59 /** 60 * Parses a commands.txt file and extracts metadata. 61 */ 62 JS::Value LoadReplayData(ScriptInterface& scriptInterface, OsPath replayFile); 63 64 /** 65 * Permanently deletes the visual replay (including the parent directory) 66 * 67 * @param replayFile path to commands.txt, whose parent directory will be deleted 68 * @return true if deletion was successful, or false on error 69 */ 70 bool DeleteReplay(const std::wstring replayFile); 71 } 72 73 #endif