Progress on multiplayer campaign:

- Moved SaveUtils to the shared project.
- Moved the "new game"/"load game" menu logic to a separate class.
- Somewhat functional campaign UI in the server lobby (only the map view is usable atm though).
This commit is contained in:
Joonas Rikkonen
2017-08-31 18:53:37 +03:00
parent c7ae91da42
commit c1f5e3cbda
18 changed files with 856 additions and 601 deletions
@@ -37,7 +37,6 @@ namespace Barotrauma
new GameModePreset("Single Player", typeof(SinglePlayerCampaign), true);
new GameModePreset("Tutorial", typeof(TutorialMode), true);
#endif
new GameModePreset("Campaign", typeof(MultiplayerCampaign), false);
var mode = new GameModePreset("SandBox", typeof(GameMode), false);
mode.Description = "A game mode with no specific objectives.";
@@ -46,6 +45,8 @@ namespace Barotrauma
mode.Description = "The crew must work together to complete a specific task, such as retrieving "
+ "an alien artifact or killing a creature that's terrorizing nearby outposts. The game ends "
+ "when the task is completed or everyone in the crew has died.";
new GameModePreset("Campaign", typeof(MultiplayerCampaign), false);
}
}
}
@@ -1,5 +1,7 @@
using System;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
@@ -7,14 +9,172 @@ namespace Barotrauma
{
class MultiplayerCampaign : CampaignMode
{
public MultiplayerCampaign(GameModePreset preset, object param) :
base(preset, param)
{
}
#if CLIENT
public static void StartCampaignSetup()
{
var setupBox = new GUIMessageBox("Campaign Setup", "", new string [0], 500, 500);
setupBox.InnerFrame.Padding = new Vector4(20.0f, 80.0f, 20.0f, 20.0f);
var newCampaignContainer = new GUIFrame(new Rectangle(0,40,0,0), null, setupBox.InnerFrame);
var loadCampaignContainer = new GUIFrame(new Rectangle(0, 40, 0, 0), null, setupBox.InnerFrame);
var campaignSetupUI = new CampaignSetupUI(true, newCampaignContainer, loadCampaignContainer);
var newCampaignButton = new GUIButton(new Rectangle(0,0,120,20), "New campaign", "", setupBox.InnerFrame);
newCampaignButton.OnClicked += (btn, obj) =>
{
newCampaignContainer.Visible = true;
loadCampaignContainer.Visible = false;
return true;
};
var loadCampaignButton = new GUIButton(new Rectangle(130, 0, 120, 20), "Load campaign", "", setupBox.InnerFrame);
loadCampaignButton.OnClicked += (btn, obj) =>
{
newCampaignContainer.Visible = false;
loadCampaignContainer.Visible = true;
return true;
};
loadCampaignContainer.Visible = false;
campaignSetupUI.StartNewGame = (Submarine sub, string saveName, string mapSeed) =>
{
GameMain.GameSession = new GameSession(sub, saveName, GameModePreset.list.Find(g => g.Name == "Campaign"));
var campaign = ((MultiplayerCampaign)GameMain.GameSession.GameMode);
campaign.GenerateMap(mapSeed);
setupBox.Close();
GameMain.NetLobbyScreen.ToggleCampaignMode(true);
};
campaignSetupUI.LoadGame = (string fileName) =>
{
SaveUtil.LoadGame(fileName);
setupBox.Close();
GameMain.NetLobbyScreen.ToggleCampaignMode(true);
};
}
#endif
public override void End(string endMessage = "")
{
isRunning = false;
bool success =
GameMain.Server.ConnectedClients.Any(c => c.inGame && c.Character != null && !c.Character.IsDead) ||
(GameMain.Server.Character != null && !GameMain.Server.Character.IsDead);
/*if (success)
{
if (subsToLeaveBehind == null || leavingSub == null)
{
DebugConsole.ThrowError("Leaving submarine not selected -> selecting the closest one");
leavingSub = GetLeavingSub();
subsToLeaveBehind = GetSubsToLeaveBehind(leavingSub);
}
}*/
GameMain.GameSession.EndRound("");
if (success)
{
bool atEndPosition = Submarine.MainSub.AtEndPosition;
/*if (leavingSub != Submarine.MainSub && !leavingSub.DockedTo.Contains(Submarine.MainSub))
{
Submarine.MainSub = leavingSub;
GameMain.GameSession.Submarine = leavingSub;
foreach (Submarine sub in subsToLeaveBehind)
{
MapEntity.mapEntityList.RemoveAll(e => e.Submarine == sub && e is LinkedSubmarine);
LinkedSubmarine.CreateDummy(leavingSub, sub);
}
}*/
if (atEndPosition)
{
Map.MoveToNextLocation();
}
SaveUtil.SaveGame(GameMain.GameSession.SaveFile);
}
if (!success)
{
/* var summaryScreen = GUIMessageBox.VisibleBox;
if (summaryScreen != null)
{
summaryScreen = summaryScreen.children[0];
summaryScreen.RemoveChild(summaryScreen.children.Find(c => c is GUIButton));
var okButton = new GUIButton(new Rectangle(-120, 0, 100, 30), "Load game", Alignment.BottomRight, "", summaryScreen);
okButton.OnClicked += GameMain.GameSession.LoadPrevious;
okButton.OnClicked += (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox); return true; };
var quitButton = new GUIButton(new Rectangle(0, 0, 100, 30), "Quit", Alignment.BottomRight, "", summaryScreen);
quitButton.OnClicked += GameMain.LobbyScreen.QuitToMainMenu;
quitButton.OnClicked += (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox); return true; };
}*/
}
for (int i = Character.CharacterList.Count - 1; i >= 0; i--)
{
Character.CharacterList[i].Remove();
}
Submarine.Unload();
}
public static MultiplayerCampaign Load(XElement element)
{
MultiplayerCampaign campaign = new MultiplayerCampaign(GameModePreset.list.Find(gm => gm.Name == "Campaign"), null);
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "map":
campaign.map = Map.Load(subElement);
break;
}
}
campaign.Money = ToolBox.GetAttributeInt(element, "money", 0);
//backwards compatibility with older save files
if (campaign.map == null)
{
string mapSeed = ToolBox.GetAttributeString(element, "mapseed", "a");
campaign.GenerateMap(mapSeed);
campaign.map.SetLocation(ToolBox.GetAttributeInt(element, "currentlocation", 0));
}
//campaign.savedOnStart = true;
return campaign;
}
public override void Save(XElement element)
{
throw new NotImplementedException();
XElement modeElement = new XElement("MultiPlayerCampaign");
modeElement.Add(new XAttribute("money", Money));
Map.Save(modeElement);
element.Add(modeElement);
}
}
}
@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using System;
using System.Xml.Linq;
namespace Barotrauma
@@ -112,14 +113,23 @@ namespace Barotrauma
#if CLIENT
CrewManager = new CrewManager();
#endif
foreach (XElement subElement in doc.Root.Elements())
{
if (subElement.Name.ToString().ToLowerInvariant() != "gamemode") continue;
GameMode = SinglePlayerCampaign.Load(subElement);
}
switch (subElement.Name.ToString().ToLowerInvariant())
{
#if CLIENT
case "gamemode": //legacy support
case "singleplayercampaign":
GameMode = SinglePlayerCampaign.Load(subElement);
break;
#endif
case "multiplayercampaign":
GameMode = MultiplayerCampaign.Load(subElement);
break;
}
}
}
private void CreateDummyLocations()
@@ -255,5 +265,32 @@ namespace Barotrauma
#endif
}
public void Save(string filePath)
{
if (!(GameMode is CampaignMode))
{
throw new NotSupportedException("GameSessions can only be saved when playing in a campaign mode.");
}
XDocument doc = new XDocument(
new XElement("Gamesession"));
var now = DateTime.Now;
doc.Root.Add(new XAttribute("savetime", now.ToShortTimeString() + ", " + now.ToShortDateString()));
doc.Root.Add(new XAttribute("submarine", submarine == null ? "" : submarine.Name));
doc.Root.Add(new XAttribute("mapseed", Map.Seed));
((CampaignMode)GameMode).Save(doc.Root);
try
{
doc.Save(filePath);
}
catch
{
DebugConsole.ThrowError("Saving gamesession to \"" + filePath + "\" failed!");
}
}
}
}
@@ -351,6 +351,31 @@ namespace Barotrauma
currentLocation = locations[index];
currentLocation.Discovered = true;
}
public void Save(XElement element)
{
XElement mapElement = new XElement("map");
mapElement.Add(new XAttribute("currentlocation", CurrentLocationIndex));
mapElement.Add(new XAttribute("seed", Seed));
mapElement.Add(new XAttribute("size", size));
List<int> discoveredLocations = new List<int>();
for (int i = 0; i < locations.Count; i++)
{
if (locations[i].Discovered) discoveredLocations.Add(i);
}
mapElement.Add(new XAttribute("discovered", string.Join(",", discoveredLocations)));
List<int> passedConnections = new List<int>();
for (int i = 0; i < connections.Count; i++)
{
if (connections[i].Passed) passedConnections.Add(i);
}
mapElement.Add(new XAttribute("passed", string.Join(",", passedConnections)));
element.Add(mapElement);
}
}
@@ -1128,8 +1128,16 @@ namespace Barotrauma.Networking
int teamCount = 1;
byte hostTeam = 1;
string levelSeed = GameMain.NetLobbyScreen.LevelSeed;
MultiplayerCampaign campaign = GameMain.GameSession?.GameMode as MultiplayerCampaign;
GameMain.GameSession = new GameSession(selectedSub, "", selectedMode, Mission.MissionTypes[GameMain.NetLobbyScreen.MissionTypeIndex]);
//don't instantiate a new gamesession if we're playing a campaign
if (campaign == null || GameMain.GameSession == null)
{
GameMain.GameSession = new GameSession(selectedSub, "", selectedMode, Mission.MissionTypes[GameMain.NetLobbyScreen.MissionTypeIndex]);
}
if (GameMain.GameSession.GameMode.Mission != null &&
GameMain.GameSession.GameMode.Mission.AssignTeamIDs(connectedClients, out hostTeam))
@@ -1141,7 +1149,14 @@ namespace Barotrauma.Networking
connectedClients.ForEach(c => c.TeamID = hostTeam);
}
GameMain.GameSession.StartRound(GameMain.NetLobbyScreen.LevelSeed, teamCount > 1);
if (campaign != null)
{
GameMain.GameSession.StartRound(campaign.Map.SelectedConnection.Level, true, teamCount > 1);
}
else
{
GameMain.GameSession.StartRound(GameMain.NetLobbyScreen.LevelSeed, teamCount > 1);
}
GameServer.Log("Starting a new round...", ServerLog.MessageType.ServerMessage);
GameServer.Log("Submarine: " + selectedSub.Name, ServerLog.MessageType.ServerMessage);
@@ -2,12 +2,14 @@
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Xml.Linq;
namespace Barotrauma
{
public partial class SaveUtil
{
public static string SaveFolder = "Data"+Path.DirectorySeparatorChar+"Saves";
public static string SaveFolder = "Data" + Path.DirectorySeparatorChar + "Saves";
public static string MultiplayerSaveFolder = "Data" + Path.DirectorySeparatorChar + "Saves" + Path.DirectorySeparatorChar + "Multiplayer";
public delegate void ProgressDelegate(string sMessage);
@@ -16,26 +18,225 @@ namespace Barotrauma
get { return Path.Combine(SaveFolder, "temp"); }
}
public enum SaveType
{
Singleplayer,
Multiplayer
}
public static void SaveGame(string filePath)
{
string tempPath = Path.Combine(SaveFolder, "temp");
Directory.CreateDirectory(tempPath);
try
{
ClearFolder(tempPath, new string[] { GameMain.GameSession.Submarine.FilePath });
}
catch
{
}
try
{
if (Submarine.MainSub != null && Submarine.Loaded.Contains(Submarine.MainSub))
{
Submarine.MainSub.FilePath = Path.Combine(tempPath, Submarine.MainSub.Name + ".sub");
Submarine.MainSub.SaveAs(Submarine.MainSub.FilePath);
}
}
catch (Exception e)
{
DebugConsole.ThrowError("Error saving submarine", e);
}
try
{
GameMain.GameSession.Save(Path.Combine(tempPath, "gamesession.xml"));
}
catch (Exception e)
{
DebugConsole.ThrowError("Error saving gamesession", e);
}
try
{
CompressDirectory(tempPath, filePath, null);
}
catch (Exception e)
{
DebugConsole.ThrowError("Error compressing save file", e);
}
}
public static void LoadGame(string filePath)
{
DecompressToDirectory(filePath, TempPath, null);
XDocument doc = ToolBox.TryLoadXml(Path.Combine(TempPath, "gamesession.xml"));
string subPath = Path.Combine(TempPath, ToolBox.GetAttributeString(doc.Root, "submarine", "")) + ".sub";
Submarine selectedMap = new Submarine(subPath, "");
GameMain.GameSession = new GameSession(selectedMap, filePath, doc);
}
public static XDocument LoadGameSessionDoc(string filePath)
{
string tempPath = Path.Combine(SaveFolder, "temp");
try
{
DecompressToDirectory(filePath, tempPath, null);
}
catch
{
return null;
}
return ToolBox.TryLoadXml(Path.Combine(tempPath, "gamesession.xml"));
}
public static void DeleteSave(string filePath)
{
//filePath = Path.Combine(SaveFolder, filePath + ".save");
try
{
File.Delete(filePath);
}
catch (Exception e)
{
DebugConsole.ThrowError("ERROR: deleting save file \"" + filePath + " failed.", e);
}
}
public static string[] GetSaveFiles(SaveType saveType)
{
string folder = saveType == SaveType.Singleplayer ? SaveFolder : MultiplayerSaveFolder;
if (!Directory.Exists(folder))
{
DebugConsole.ThrowError("Save folder \"" + folder + " not found! Attempting to create a new folder");
try
{
Directory.CreateDirectory(folder);
}
catch (Exception e)
{
DebugConsole.ThrowError("Failed to create the folder \"" + folder + "\"!", e);
}
}
string[] files = Directory.GetFiles(folder, "*.save");
/*for (int i = 0; i < files.Length; i++)
{
files[i] = Path.GetFileNameWithoutExtension(files[i]);
}*/
return files;
}
public static string CreateSavePath(string fileName = "Save")
{
if (!Directory.Exists(SaveFolder))
{
DebugConsole.ThrowError("Save folder \"" + SaveFolder + "\" not found. Created new folder");
Directory.CreateDirectory(SaveFolder);
}
string extension = ".save";
string pathWithoutExtension = Path.Combine(SaveFolder, fileName);
int i = 0;
while (File.Exists(pathWithoutExtension + " " + i + extension))
{
i++;
}
return pathWithoutExtension + " " + i;
}
public static void CompressStringToFile(string fileName, string value)
{
// A.
// Write string to temporary file.
string temp = Path.GetTempFileName();
File.WriteAllText(temp, value);
// B.
// Read file into byte array buffer.
byte[] b;
using (FileStream f = new FileStream(temp, FileMode.Open))
{
b = new byte[f.Length];
f.Read(b, 0, (int)f.Length);
}
// C.
// Use GZipStream to write compressed bytes to target file.
using (FileStream f2 = new FileStream(fileName, FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
gz.Write(b, 0, b.Length);
}
}
public static void CompressFile(string sDir, string sRelativePath, GZipStream zipStream)
{
//Compress file name
char[] chars = sRelativePath.ToCharArray();
zipStream.Write(BitConverter.GetBytes(chars.Length), 0, sizeof(int));
foreach (char c in chars)
zipStream.Write(BitConverter.GetBytes(c), 0, sizeof(char));
//Compress file content
byte[] bytes = File.ReadAllBytes(Path.Combine(sDir, sRelativePath));
zipStream.Write(BitConverter.GetBytes(bytes.Length), 0, sizeof(int));
zipStream.Write(bytes, 0, bytes.Length);
}
public static void CompressDirectory(string sInDir, string sOutFile, ProgressDelegate progress)
{
string[] sFiles = Directory.GetFiles(sInDir, "*.*", SearchOption.AllDirectories);
int iDirLen = sInDir[sInDir.Length - 1] == Path.DirectorySeparatorChar ? sInDir.Length : sInDir.Length + 1;
using (FileStream outFile = new FileStream(sOutFile, FileMode.Create, FileAccess.Write, FileShare.None))
using (GZipStream str = new GZipStream(outFile, CompressionMode.Compress))
foreach (string sFilePath in sFiles)
{
string sRelativePath = sFilePath.Substring(iDirLen);
if (progress != null)
progress(sRelativePath);
CompressFile(sInDir, sRelativePath, str);
}
}
public static Stream DecompressFiletoStream(string fileName)
{
if (!File.Exists(fileName))
{
DebugConsole.ThrowError("File \""+fileName+" doesn't exist!");
DebugConsole.ThrowError("File \"" + fileName + " doesn't exist!");
return null;
}
using (FileStream originalFileStream = new FileStream(fileName, FileMode.Open))
{
MemoryStream decompressedFileStream = new MemoryStream();
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
return decompressedFileStream;
}
}
}
}
public static bool DecompressFile(string sDir, GZipStream zipStream, ProgressDelegate progress)
{
//Decompress file name
@@ -75,12 +276,41 @@ namespace Barotrauma
return true;
}
public static void DecompressToDirectory(string sCompressedFile, string sDir, ProgressDelegate progress)
{
using (FileStream inFile = new FileStream(sCompressedFile, FileMode.Open, FileAccess.Read, FileShare.None))
using (GZipStream zipStream = new GZipStream(inFile, CompressionMode.Decompress, true))
while (DecompressFile(sDir, zipStream, progress)) ;
}
private static void ClearFolder(string FolderName, string[] ignoredFiles = null)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
bool ignore = false;
foreach (string ignoredFile in ignoredFiles)
{
if (Path.GetFullPath(fi.FullName).Equals(Path.GetFullPath(ignoredFile)))
{
ignore = true;
break;
}
}
if (ignore) continue;
fi.IsReadOnly = false;
fi.Delete();
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName, ignoredFiles);
di.Delete();
}
}
}
}