private void DeserializeMap(string json) { MapJSON map = JsonConvert.DeserializeObject <MapJSON>(json); int x = map.mapRows.Length; int y = map.mapRows[0].row.Split(',').Length; TileValues = new int[x, y]; for (int i = 0; i < x; i++) { string[] rowValues = map.mapRows[i].row.Split(','); for (int j = 0; j < y; j++) { int value; TileValues[i, j] = (int.TryParse(rowValues[j], out value) ? value : 0); if (TileValues[i, j] != 0) { var mapPrefab = TileStatus.GetMapPrefabById(TileValues[i, j]); Instantiate(mapPrefab, new Vector3(i * 1f, 0, j * 1f), Quaternion.identity); } } } }
public MapJSON GetCurrentMap() { Color bgColor = MainWindowViewModel.viewModel.BackgroundColor; MapJSON map = new MapJSON() { BackgroundR = bgColor.R, BackgroundG = bgColor.G, BackgroundB = bgColor.B }; foreach (GameObject obj in MainWindowViewModel.viewModel.objectManager.GetObjects()) { MapGameObject mapObject = obj as MapGameObject; if (mapObject != null) { map.Objects.Add(new MapObjectJSON() { Layer = mapObject.Layer, PositionX = mapObject.GetPosition().X, PositionY = mapObject.GetPosition().Y, Properties = mapObject.Properties, Info = mapObject.Info, Name = mapObject.Name, Components = mapObject.Components }); } } return(map); }
public void SaveProject(bool forceDialog = false) { Mouse.OverrideCursor = Cursors.AppStarting; if (projectManager.ProjectPath == string.Empty || forceDialog) { SaveFileDialog projectDialog = new SaveFileDialog(); projectDialog.Filter = "Pest Control Map Project (*.mapproj)|*.mapproj"; // (== true instead of just leaving it because ShowDialog() returns a nullable bool instead of a regular bool) if (projectDialog.ShowDialog() == true) { var stream = File.Create(projectDialog.FileName); projectManager.ProjectPath = projectDialog.FileName; // Always make sure to dispose your streams, kids. stream.Dispose(); } else { // If the user cancels the save file dialog, cancel saving entirely. Mouse.OverrideCursor = null; return; } } // We now are certain the project file exists if we've gotten this far in the scope, write to it. MapJSON map = GetCurrentMap(); string jsonOutput = JsonConvert.SerializeObject(map, Formatting.Indented); File.WriteAllText(projectManager.ProjectPath, jsonOutput); Mouse.OverrideCursor = null; }
public IJSON ToJSON() { MapJSON json = new MapJSON(); json.width = layout.width; json.height = layout.height; json.imagePath = "./Resources/maps/"+layout.name+".png"; return json; }
public IJSON ToJSON() { MapJSON json = new MapJSON(); json.width = layout.width; json.height = layout.height; json.imagePath = "./Resources/maps/" + layout.name + ".png"; return(json); }
private void MenuItem_Export(object sender, RoutedEventArgs e) { SaveFileDialog projectDialog = new SaveFileDialog(); projectDialog.Filter = "Pest Control Map Project (*.pcmap)|*.pcmap"; if (projectDialog.ShowDialog() == true) { MapJSON map = GetCurrentMap(); map.WriteBinaryMapFile(projectDialog.FileName); } }
public static Map LoadMap(ModAssetInfo mapFile, GameCore game) { if (mapFile.AssetName == null) { return(new Map(game));// it's null } var data = mapFile.ReadAsString(); var map = new Map(game, MapJSON.Load(data), data); map.AssetInfo = mapFile; return(map); }
private Map(GameCore game, MapJSON deserialized, string mapData) { _game = game; _deserialized = deserialized; _data = mapData; if (_deserialized.ShadowOffset == null) { ShadowOffset = new Vector2(0.25f, -0.25f); } else { ShadowOffset = _deserialized.ShadowOffset; } if (_deserialized.ShadowColor == null) { ShadowColor = new Color(50, 50, 50, 100); } else { ShadowColor = _deserialized.ShadowColor; } if (_deserialized.BackgroundColor == null) { BackgroundColor = Color.DarkGray; } else { BackgroundColor = _deserialized.BackgroundColor; } //Process basic if (_deserialized.Spawns != null) { foreach (var team in _deserialized.Spawns) { var ts = new TeamSpawn(); ts.TeamIndex = team.TeamIndex; foreach (var pos in team.SpawnPositions) { ts.Positions.Add(new TeamSpawn.SpawnPosition(pos)); } _spawnsByTeam.Add(team.TeamIndex, ts); } } }
private void UI_ShowPrimaryMenu() { _ui.UnwindAndEmpty(); _ui.GoToPageIfNotThere("mapmakermainmenu", page => { page.Element <Button>("LoadMapBtn").Click += (a, b) => { var fd = new System.Windows.Forms.OpenFileDialog(); fd.Filter = "MP Tanks 2D map files (*.json)|*.json"; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (!File.Exists(fd.FileName)) { return; } try { _game = _map.CreateFromMap(MapJSON.Load( File.ReadAllText(fd.FileName))); _renderer.Game = _game; } catch { _ui.ShowMessageBox("Load error", "An error occurred while loading that map.", UserInterface.MessageBoxType.ErrorMessageBox); } } }; page.Element <Button>("SaveMapBtn").Click += (a, b) => { var fd = new System.Windows.Forms.SaveFileDialog(); fd.Filter = "MP Tanks 2D map files (*.json)|*.json"; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (!Directory.Exists(new FileInfo(fd.FileName).Directory.FullName)) { return; } try { File.WriteAllText(fd.FileName, _map.GenerateMap(_game)); } catch { _ui.ShowMessageBox("Save error!", "An error occurred while saving that map for you.", UserInterface.MessageBoxType.ErrorMessageBox); } } }; page.Element <StackPanel>("ModsListPanel"); page.Element <Button>("LoadModBtn").Click += (a, b) => UI_LoadMod(); page.Element <CheckBox>("LockToGridChkBox", elem => { elem.Checked += (a, b) => UI_LockToGrid = true; elem.Unchecked += (a, b) => UI_LockToGrid = false; }); page.Element <TextBox>("SearchBox", elem => { elem.KeyUp += (a, b) => { var selector = page.Element <StackPanel>("MapObjectSelectorPanel"); foreach (var itm in selector.Children) { var info = Engine.Helpers.ReflectionHelper.GetGameObjectInfo((string)itm.Tag); if (info.DisplayName.ToLower().Contains(elem.Text.ToLower()) || info.DisplayDescription.ToLower().Contains(elem.Text.ToLower())) { //Visible itm.Visibility = EmptyKeys.UserInterface.Visibility.Visible; } else { itm.Visibility = EmptyKeys.UserInterface.Visibility.Collapsed; } } }; }); page.Element <StackPanel>("MapObjectSelectorPanel"); page.Element <Button>("MoreSettingsBtn").Click += (a, b) => UI_ShowMoreSettingsMenu(); }, (page, state) => { //update types var modListPanel = page.Element <StackPanel>("ModsListPanel"); foreach (var mod in _map.Mods) { var existing = modListPanel.Children.FirstOrDefault(a => a.Tag.Equals(mod)); if (existing != null) { //it exists, ignore it } else { var tblk = new TextBlock(); tblk.Tag = mod; tblk.Text = mod.ModName + "(v" + mod.ModMajor + "." + mod.ModMinor + ")"; tblk.FontFamily = new FontFamily("JHUF"); tblk.FontSize = 12; tblk.Foreground = new SolidColorBrush(ColorW.White); tblk.HorizontalContentAlignment = EmptyKeys.UserInterface.HorizontalAlignment.Center; tblk.Padding = new EmptyKeys.UserInterface.Thickness(5); modListPanel.Children.Add(tblk); } } //update map object types var selector = page.Element <StackPanel>("MapObjectSelectorPanel"); //get all map objects and their information foreach (var mapObjReflName in Engine.Maps.MapObjects.MapObject.AvailableTypes.Keys) { var info = Engine.Helpers.ReflectionHelper.GetGameObjectInfo(mapObjReflName); var existing = (Button)selector.Children.FirstOrDefault(a => a.Tag as string == mapObjReflName); if (existing != null) { //It exists, ignore it } else { //create one var btn = new Button(); var panel = new StackPanel(); var head = new TextBlock(); var desc = new TextBlock(); head.FontFamily = new FontFamily("JHUF"); head.FontSize = 12; head.Text = info.DisplayName; head.Width = 175; desc.FontFamily = new FontFamily("JHUF"); desc.FontSize = 12; desc.Text = UserInterface.SplitStringIntoLines(info.DisplayDescription, 28); desc.Width = 175; desc.HorizontalAlignment = EmptyKeys.UserInterface.HorizontalAlignment.Center; desc.Foreground = new SolidColorBrush(new ColorW(Color.Gray.R, Color.Gray.G, Color.Gray.B)); panel.Orientation = EmptyKeys.UserInterface.Orientation.Vertical; panel.Width = 175; panel.Children.Add(head); panel.Children.Add(desc); btn.Content = panel; btn.Width = 175; btn.Tag = mapObjReflName; btn.Padding = new EmptyKeys.UserInterface.Thickness(0, 0, 0, 10); btn.Click += (a, b) => { //Spawn and select an object var reflName = (string)btn.Tag; var obj = _game.AddMapObject(reflName); obj.Position = UI_ComputeWorldSpaceFromMouse( new Vector2( Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2 )); }; selector.Children.Add(btn); } } }); _ui.UpdateState(new object()); }
public static Map Load(string map, GameCore game) { var m = new Map(game, MapJSON.Load(map), map); return(m); }
private MapJSON CreateMapFromGame(GameCore game) { var mapJSON = new MapJSON(); //Find all of the objects and spawns var objs = game.GameObjects.Where(a => a.GetType().FullName != "MPTanks.CoreAssets.MapObjects.SpawnPoint") .Where(a => a.GetType().IsSubclassOf(typeof(Engine.Maps.MapObjects.MapObject))) .Select(a => (Engine.Maps.MapObjects.MapObject)a); var spawns = game.GameObjects.Where(a => a.GetType().FullName == "MPTanks.CoreAssets.MapObjects.SpawnPoint") .Select(a => (dynamic)a); //Cast to dynamic because we *cannot* preload the CoreAssets assembly //Remap the spawns from SpawnPoint mapobjects to "spawns" in map terms //Find out how many teams var teams = spawns.Select(a => a.Team).Distinct() .Select(a => new MapTeamsJSON() { TeamIndex = a }) .ToArray(); //And append the spawn points foreach (var team in teams) { team.SpawnPositions = spawns .Where(a => a.Team == team.TeamIndex) .Select(a => a.Position) .Select(a => new JSONVector { X = a.X, Y = a.Y }) .ToArray(); } mapJSON.Spawns = teams; //Map all of the objects mapJSON.Objects = objs.Select(a => new MapObjectJSON { ConfiguredSettings = a.InstanceSettings.ToDictionary(b => b.Key, b => b.Value), DesiredSize = a.Size, DrawLayer = a.DrawLayer, Mask = a.ColorMask, Position = a.Position, ReflectionName = a.ReflectionName, Rotation = a.Rotation }).ToArray(); mapJSON.ModDependencies = Mods.Select(a => a.ModName + ":" + a.ModMajor + "." + a.ModMinor).ToArray(); //And find the map size Vector2 min = new Vector2(float.PositiveInfinity), max = new Vector2(float.NegativeInfinity); //Loop through the bounding boxes of each object and find the minimum and maximum foreach (var obj in game.GameObjects) { //Get the aabb var aabbs = obj.Body.FixtureList.Select(a => { Transform tf; obj.Body.GetTransform(out tf); AABB aabb; a.Shape.ComputeAABB(out aabb, ref tf, 0); return(aabb); }); foreach (var ab in aabbs) { foreach (var vertF in ab.Vertices) { var vert = vertF; vert /= game.Settings.PhysicsScale; if (vert.X > max.X) { max.X = vert.X; } if (vert.Y > max.Y) { max.Y = vert.Y; } if (vert.X < min.X) { min.X = vert.X; } if (vert.Y < min.Y) { min.Y = vert.Y; } } } } mapJSON.Size = new JSONVector { X = max.X - min.X, Y = max.Y - min.Y }; mapJSON.TopLeft = min; mapJSON.BottomRight = max; mapJSON.Author = MapAuthor; mapJSON.Name = MapName; mapJSON.ShadowColor = ShadowColor; mapJSON.ShadowOffset = ShadowOffset; mapJSON.BackgroundColor = BackgroundColor; return(mapJSON); }
private GameCore CreateGameFromMapAndUpdateModsList(MapJSON map) { MapName = map.Name; MapAuthor = map.Author; BackgroundColor = map.BackgroundColor; ShadowColor = map.ShadowColor; ShadowOffset = map.ShadowOffset; var game = new GameCore(null, new NullGamemode(), Newtonsoft.Json.JsonConvert.SerializeObject(map)); game.Authoritative = true; game.BeginGame(true); //Blow up the mod infos var deps = map.ModDependencies.Select(a => { var name = a.Split(':')[0]; var major = int.Parse(a.Split(':')[1].Split('.')[0]); var minor = int.Parse(a.Split(':')[1].Split('.')[1].Split('-')[0]); return(new Modding.ModInfo() { ModName = name, ModMajor = major, ModMinor = minor }); }); //And make sure they're loaded foreach (var itm in deps) { var db = Modding.ModDatabase.Get(itm.ModName, itm.ModMajor); if (db == null || db.Minor < itm.ModMinor) { throw new Exception($"Mod {db.Name} v{db.Major}.{db.Minor} not found or is out of date."); } string err; var mod = db.LoadIfNotLoaded(GameSettings.Instance.ModUnpackPath, GameSettings.Instance.ModMapPath, GameSettings.Instance.ModAssetPath, out err); if (mod == null) { throw new Exception($"Failed to load mod {db.Name} v{db.Major}.{db.Minor}", new Exception(err)); } } Mods = deps.ToList(); //Recreate the SpawnPoint objects from the map spawns list //TODO: Figure out why this doesn't work correctly foreach (var teamSpawns in map.Spawns) { foreach (var pos in teamSpawns.SpawnPositions) { var gObj = game.AddMapObject("CoreAssets+SpawnPoint", true); gObj.SetInstanceSetting("Team Number", teamSpawns.TeamIndex.ToString()); gObj.Position = pos; } } return(game); }
public GameCore CreateFromMap(MapJSON map) => CreateGameFromMapAndUpdateModsList(map);
public void OpenProject() { OpenFileDialog projectDialog = new OpenFileDialog(); projectDialog.Filter = "Pest Control Map Project (*.mapproj)|*.mapproj"; if (projectDialog.ShowDialog() == true) { projectManager.ProjectPath = projectDialog.FileName; // Clear objects of map objects List <MapGameObject> toRemove = new List <MapGameObject>(); foreach (GameObject obj in MainWindowViewModel.viewModel.objectManager.GetObjects()) { MapGameObject mapObject = obj as MapGameObject; if (mapObject != null) { toRemove.Add(mapObject); } } foreach (MapGameObject obj in toRemove) { MainWindowViewModel.viewModel.objectManager.GetObjects().Remove(obj); } // Add new map objects from json file string jsonInput = File.ReadAllText(projectDialog.FileName); MapJSON map = JsonConvert.DeserializeObject <MapJSON>(jsonInput); MainWindowViewModel.viewModel.BackgroundColor = new Color(map.BackgroundR, map.BackgroundG, map.BackgroundB); foreach (MapObjectJSON objectJson in map.Objects) { MapGameObject mapObject = new MapGameObject(objectJson.Info) { Properties = objectJson.Properties, Layer = objectJson.Layer, Name = objectJson.Name, HelperRectangles = objectJson.Info.HelperRectangles, Components = objectJson.Components }; mapObject.SetPosition(new Vector2(objectJson.PositionX, objectJson.PositionY)); mapObject.CurrentAnimation = objectJson.Info.DefaultAnimation; MainWindowViewModel.viewModel.objectManager.GetObjects().Add(mapObject); } } else { return; } // Update background color box Color backColor = MainWindowViewModel.viewModel.BackgroundColor; BackColorTextBox.Text = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(255, backColor.R, backColor.G, backColor.B)); UpdateTitleBar(); }