public Image GetImage(MapDescriptor descriptor) { string filename = descriptor.CalculateFilename(); if (File.Exists(filename)) { Image image = null; descriptor.MapState = MapDescriptor.MapImageState.Correct; try { System.Threading.Thread.Sleep(10); image = Bitmap.FromFile(filename); return image; } catch (OutOfMemoryException) { if (image != null) { image.Dispose(); image = null; } } } descriptor.MapState = MapDescriptor.MapImageState.Empty; return null; }
private void readRotationOriginPoints(VAVAddr address, EndianBinaryReader s, MapDescriptor mapDescriptor, AddressMapper addressMapper) { mapDescriptor.SwitchRotationOriginPoints.Clear(); // Special case handling: in the original game these values are initialized at run time only. So we need to hardcode them: if (address == addressMapper.toVersionAgnosticAddress((BSVAddr)0x806b8df0)) // magmageddon { // no points } else if (address == addressMapper.toVersionAgnosticAddress((BSVAddr)0x8047d598)) // collosus { mapDescriptor.SwitchRotationOriginPoints[0] = new OriginPoint(-288, -32); mapDescriptor.SwitchRotationOriginPoints[1] = new OriginPoint(288, -32); } else if (address == addressMapper.toVersionAgnosticAddress((BSVAddr)0x8047d5b4)) // observatory { mapDescriptor.SwitchRotationOriginPoints[0] = new OriginPoint(0, 0); } else if (addressMapper.canConvertToFileAddress(address)) { s.Seek(addressMapper.toFileAddress(address), SeekOrigin.Begin); var originPointCount = s.ReadUInt32(); for (int i = 0; i < originPointCount; i++) { OriginPoint point = new OriginPoint(); point.X = s.ReadSingle(); var z = s.ReadSingle(); // ignore Z value point.Y = s.ReadSingle(); mapDescriptor.SwitchRotationOriginPoints[i] = point; } } }
public void CreateWorld(MapDescriptor descriptor, MapController map, PortalController portals, CameraController camera, Transform parent) { GameObject[, ][] worldTemplate = descriptor.Map; for (int x = 0; x < worldTemplate.GetLength(0); x++) { for (int y = 0; y < worldTemplate.GetLength(1); y++) { foreach (GameObject mapObj in worldTemplate[x, y]) { MapObjectBehaviour behaviour = Object.Instantiate(mapObj, new Vector3(x, y), Quaternion.identity).GetComponent <MapObjectBehaviour>(); behaviour.gameObject.SetActive(true); behaviour.transform.SetParent(parent); behaviour.AssignDescriptor(mapObj.GetComponent <MapObjectBehaviour>().CopyDescriptor()); behaviour.Initialize(); if (isPlayer(behaviour)) { handleSetupPlayer(behaviour, map); } if (isPortal(behaviour)) { handleSetupPortal(behaviour, portals); } } } } Sprite background = new SpriteLoader().Load(descriptor.BackgroundSprite); camera.SetBackground(background); }
public void ReadXElement_Empty_ThrowsSyncDocumentException() { MapDescriptor mapDescriptor = new MapDescriptor(); XElement element = XElement.Parse("<NotMap />"); mapDescriptor.ReadXElement(element); }
public MapDescriptor ParseWorld(string mapName, string[,] worldKeys) { int width = worldKeys.GetLength(0); int height = worldKeys.GetLength(1); GameObject[, ][] world = new GameObject[width, height][]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { string keysInCell = worldKeys[x, y]; if (string.IsNullOrEmpty(keysInCell)) { world[x, y] = new GameObject[0]; } else { string[] keys = worldKeys[x, y].Split(joinKey.ToCharArray()); world[x, y] = parseObjectsAtPosition(keys, x, y); } } } MapDescriptor descriptor = new MapDescriptor(mapName, world); JSONParser metaDataParser = new JSONParser(); metaDataParser.ParseJSONOverwriteFromResources(getMetaFileName(mapName), descriptor); return(descriptor); }
private async Task exportMdAsync(MapDescriptor mapDescriptor) { if (mapDescriptor == null) { return; } SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Map Descriptor file and accompanying files|*.md"; saveFileDialog1.Title = "Where shall the map files be exported?"; saveFileDialog1.FileName = mapDescriptor.InternalName + ".md"; saveFileDialog1.OverwritePrompt = false; if (saveFileDialog1.ShowDialog(this) == DialogResult.OK && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName)) { using (var cancelTokenSource = new CancellationTokenSource()) using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(exitTokenSource.Token, cancelTokenSource.Token)) { CancellationToken ct = linkedTokenSource.Token; ProgressBar progressBar = new ProgressBar(verboseToolStripMenuItem.Checked); progressBar.callback = (b) => { try { cancelTokenSource?.Cancel(); } catch (ObjectDisposedException) { } }; progressBar.Show(this); var progress = new Progress <ProgressInfo>(progressInfo => { progressBar.update(progressInfo); Debug.WriteLine(progressInfo.line); }); bool overwrite = false; tryExportMd: try { var input = setInputISOLocation.Text; input = PatchProcess.DoPathCorrections(input, false); input = PatchProcess.GetCachePath(input); PatchProcess.ExportMd(saveFileDialog1.FileName, input, mapDescriptor, overwrite, progress, ct); } catch (FileAlreadyExistException e1) { DialogResult dialogResult = MessageBox.Show(e1.Message.Replace("\n", Environment.NewLine) + Environment.NewLine + "Do you want to overwrite these files?", "Files already exist", MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.OK) { overwrite = true; goto tryExportMd; } } catch (Exception e) { progressBar.appendText(e.Message); progressBar.appendText(Environment.NewLine + Environment.NewLine + e.ToString()); progressBar.EnableButton(); Debug.WriteLine(e.ToString()); } } } }
void Start() { MapDescriptor desc = ReadMap(); listCells = new List <GameObject>(); BuildMap(desc); DisplayMiniMap(); }
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) { MapDescriptor mapDescriptor = dataGridView1.Rows[e.RowIndex].DataBoundItem as MapDescriptor; if (mapDescriptor != null && mapDescriptor.Dirty) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightYellow; } }
void Start() { this.cam = CameraController.Get; this.currentMap = parseMap(startingMapName); if (createMapOnStart) { createMap(currentMap); } }
public static System.Version ComputeAndroidVersion(MapDescriptor mapDescriptor) { System.Version requiredVersion = new System.Version("1.0.0"); System.Version v110 = new System.Version("1.1.0"); if (mapDescriptor.SlowJumpLimit != 6.5f || mapDescriptor.SlowJumpMultiplier != 1.1f || mapDescriptor.FastJumpLimit != 8.5f || mapDescriptor.FastJumpMultiplier != 1.3f) { requiredVersion = MaxVersion(requiredVersion, v110); } return(requiredVersion); }
private void readLoopingModeConfig(VAVAddr address, EndianBinaryReader s, MapDescriptor mapDescriptor, AddressMapper addressMapper) { if (addressMapper.canConvertToFileAddress(address)) { s.Seek(addressMapper.toFileAddress(address), SeekOrigin.Begin); mapDescriptor.LoopingModeRadius = s.ReadSingle(); mapDescriptor.LoopingModeHorizontalPadding = s.ReadSingle(); mapDescriptor.LoopingModeVerticalSquareCount = s.ReadSingle(); } }
public void GetXElement_SetVersion_ReturnsCorrectXml() { MapDescriptor mapDescriptor = new MapDescriptor(); mapDescriptor.Script = "script"; mapDescriptor.Version = 4; mapDescriptor.Designer = new XElement("Designer").ToString(); var element = mapDescriptor.GetXElement(); Assert.IsTrue(element.Attribute(MapDescriptor.CN_VERSION).Value == mapDescriptor.Version.ToString()); }
public void GetXElement_SetDesigner_ReturnsCorrectXml() { MapDescriptor mapDescriptor = new MapDescriptor(); mapDescriptor.Script = "script"; mapDescriptor.Version = 4; mapDescriptor.Designer = new XElement("Designer").ToString(); var element = mapDescriptor.GetXElement(); Assert.IsTrue(element.Element(MapDescriptor.CN_DESIGNER) != null); }
// Overwrites any existing map in the lookup void trackMap(MapDescriptor descriptor) { if (mapBuffer.ContainsKey(descriptor.MapName)) { mapBuffer[descriptor.MapName] = descriptor; } else { mapBuffer.Add(descriptor.MapName, descriptor); } }
public void GetXElement_AllPropertiesFiled_Has2Attributes1ChildNode() { MapDescriptor mapDescriptor = new MapDescriptor(); mapDescriptor.Script = "script"; mapDescriptor.Version = 4; mapDescriptor.Designer = new XElement("Designer").ToString(); var element = mapDescriptor.GetXElement(); Assert.IsTrue(element.Attributes().Count() == 2, "MapDescriptor have to have 2 attributes"); Assert.IsTrue(element.Elements().Count() == 1, "MapDescriptor have to have 1 child node"); }
public Image GetImageFromFile(MapDescriptor description) { nullImage.Text += "\n" + description; description.MapState = MapDescriptor.MapImageState.Partial; using (Image image = fileAccessor.GetImage(description)) { if (image == null) return null; RectangleF bounds = EarthProjection.CalculateImageBoundsAtLatitude(image.Width, image.Height, description.Latitude); Image ret = ImageConverter.CropImage(image, bounds); return ret; } }
public Map(Vector2 dimensions, string name) { _descriptor = new MapDescriptor(dimensions, name); _layers = new Dictionary <string, Layer>(); _tilesets = new Dictionary <string, Texture2D>(); this.AddLayer("Ground", new Layer(this.Descriptor.Dimensions, "Ground", 0)); this.AddLayer("Mask1", new Layer(this.Descriptor.Dimensions, "Mask1", 1)); this.AddLayer("Mask2", new Layer(this.Descriptor.Dimensions, "Mask2", 2)); this.AddLayer("Fringe", new Layer(this.Descriptor.Dimensions, "Fringe", 3)); }
public Map(MapDescriptor descriptor) { _mapDescriptor = descriptor; _layers = new Dictionary <string, Layer>(); _actors = new WorldDictionary <long, IActor <IActorDescriptor> >(); _actorCollidingObjects = new WorldDictionary <IActor <IActorDescriptor>, List <MapObject> >(); _playerSpawnAreas = new List <Tuple <Vector, Layer> >(); _pathFinders = new Dictionary <Layer, Pathfinder>(); _mapItems = new List <MapItem>(); this.Initalize(); }
public static PackageJSON MapDescriptorToJSON(MapDescriptor mapDescriptor) { PackageJSON packageJSON = new PackageJSON(); packageJSON.descriptor = new Descriptor(); packageJSON.config = new Config(); packageJSON.descriptor.author = mapDescriptor.AuthorName; packageJSON.descriptor.objectName = mapDescriptor.MapName; packageJSON.descriptor.description = mapDescriptor.Description; packageJSON.config.imagePath = null; packageJSON.config.gravity = mapDescriptor.GravitySpeed; // do config stuff here return(packageJSON); }
public TileMap(string fileName) { string[] gridLines = File.ReadAllLines(fileName); Descriptor = CreateMapDescriptor(gridLines[0]); Grid = new int[Descriptor.SizeX, Descriptor.SizeY]; for (int y = 0; y < Descriptor.SizeY; y++) { int[] row = GetRow(gridLines[y + 1]); for (int x = 0; x < Descriptor.SizeX; x++) { Grid[y, x] = row[x]; } } }
protected override void writeAsm(EndianBinaryWriter stream, AddressMapper addressMapper, List <MapDescriptor> mapDescriptors) { short easyPracticeBoard = -1; short standardPracticeBoard = -1; var validation = MapDescriptor.getPracticeBoards(mapDescriptors, out easyPracticeBoard, out standardPracticeBoard); if (!validation.Passed) { throw new ArgumentException(validation.GetMessage("\n")); } // li r0,0x29 -> li r0,easyPracticeBoard stream.Seek(addressMapper.toFileAddress((BSVAddr)0x80173bf8), SeekOrigin.Begin); stream.Write(PowerPcAsm.li(0, easyPracticeBoard)); // li r0,0x14 -> li r0,standardPracticeBoard stream.Seek(addressMapper.toFileAddress((BSVAddr)0x80173c04), SeekOrigin.Begin); stream.Write(PowerPcAsm.li(0, standardPracticeBoard)); }
public Map(MapDescriptor descriptor, TextureLoader textureLoader) : this() { _descriptor = descriptor; _descriptor.DimensionsChanged += (sender, args) => { if (_layers != null) { foreach (var layer in _layers.Values) { layer.Resize(this.Descriptor.Dimensions); } } this.Map_Resized?.Invoke(this, new EventArgs()); }; }
private void importMd(MapDescriptor mapDescriptor) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Map Descriptor File (.md)|*.md"; openFileDialog1.Title = "Which Map to import?"; if (openFileDialog1.ShowDialog(this) == DialogResult.OK && !string.IsNullOrWhiteSpace(openFileDialog1.FileName)) { using (var cancelTokenSource = new CancellationTokenSource()) using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(exitTokenSource.Token, cancelTokenSource.Token)) { CancellationToken ct = linkedTokenSource.Token; ProgressBar progressBar = new ProgressBar(verboseToolStripMenuItem.Checked); progressBar.callback = (b) => { try { cancelTokenSource?.Cancel(); } catch (ObjectDisposedException) { } }; progressBar.Show(this); var progress = new Progress <ProgressInfo>(progressInfo => { progressBar.update(progressInfo); Debug.WriteLine(progressInfo.line); }); try { var importedMapDescriptor = PatchProcess.ImportMd(openFileDialog1.FileName, progress, ct); if (mapDescriptor != null) { mapDescriptor.setFromImport(importedMapDescriptor); } else { BindingSource bs = dataGridView1.DataSource as BindingSource; bs.Add(importedMapDescriptor); } } catch (Exception e) { progressBar.appendText(e.Message); progressBar.appendText(Environment.NewLine + Environment.NewLine + e.ToString()); progressBar.EnableButton(); Debug.WriteLine(e.ToString()); } } } }
private void BuildMap(MapDescriptor pDesc) { float MAX_WIDTH = pDesc.width * CELL_WIDTH; float MAX_HEIGHT = pDesc.height * CELL_HEIGHT; float left = -MAX_WIDTH * 0.5f; float up = MAX_HEIGHT * 0.5f; for (int col = 0; col < pDesc.width; ++col) { for (int line = 0; line < pDesc.height; ++line) { int cellValue = pDesc.grid[col, line]; // CREATE OBJECT Vector3 pos = new Vector3(left + col * CELL_WIDTH, up - line * CELL_HEIGHT, 0f); GameObject cell = CreateCell(col, line, cellValue, pos); } } }
private async void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0) { MapDescriptor mapDescriptor = senderGrid.Rows[e.RowIndex].DataBoundItem as MapDescriptor; if (senderGrid.Columns[e.ColumnIndex].Name.ToLower().Contains("export")) { await exportMdAsync(mapDescriptor); } else if (senderGrid.Columns[e.ColumnIndex].Name.ToLower().Contains("import")) { importMd(mapDescriptor); } else if (senderGrid.Columns[e.ColumnIndex].Name.ToLower().Contains("venturecards")) { new VentureCardBox(mapDescriptor.VentureCard).ShowDialog(this); } } }
public List <MapDescriptor> readMainDol(EndianBinaryReader stream, IProgress <ProgressInfo> progress) { // GetMapCount stream.Seek(addressMapper.toFileAddress((BSVAddr)0x801cca30), SeekOrigin.Begin); UInt32 opcode = stream.ReadUInt32(); var count = (Int16)(PowerPcAsm.getOpcodeParameter(opcode)); List <MapDescriptor> mapDescriptors = new List <MapDescriptor>(); for (int i = 0; i < count; i++) { MapDescriptor mapDescriptor = new MapDescriptor(); mapDescriptors.Add(mapDescriptor); } foreach (var patch in patches) { patch.read(stream, addressMapper, mapDescriptors, progress); } return(mapDescriptors); }
/// <summary> /// /// </summary> /// <param name="entityDescriptor"></param> public EntityResultMapper(EntityDescriptor entityDescriptor) { if (entityDescriptor == null) { throw new ArgumentNullException(nameof(entityDescriptor)); } var entityDescriptors = new Dictionary <string, MapDescriptor>(StringComparer.CurrentCultureIgnoreCase); foreach (var member in entityDescriptor.Members) { MapDescriptor descriptor = new MapDescriptor(); descriptor.MemberName = member.Name; descriptor.MemberType = member.Member.MemberType; descriptor.MemberValueType = member.Type.ToString(); descriptor.ValueType = member.Type; descriptor.Map = CreateMapDelegate(member.Member); entityDescriptors[member.Name] = descriptor; } this.memberDescriptors = entityDescriptors; }
/* Function to drawing map */ private void BuildMap(MapDescriptor pDescriptor) { MAP_MAX_WIDTH = pDescriptor.width * CELL_WIDTH; MAP_MAX_HEIGHT = pDescriptor.height * CELL_HEIGHT; float left = -MAP_MAX_WIDTH * 0.5f; float up = MAP_MAX_HEIGHT * 0.5f; for (int c = 0; c < pDescriptor.width; ++c) // Columns { for (int l = 0; l < pDescriptor.height; l++) // Lines { int cellValue = pDescriptor.grid[c, l]; Vector3 cellPosition = new Vector3( c * CELL_WIDTH, l * CELL_HEIGHT, 0f ); /* Creating object */ CreateCell(c, l, cellValue, cellPosition); } } }
public Map(MapDescriptor <LayerDescriptor <TileDescriptor <SpriteInfo> > > descriptor) { _actors = new WorldDictionary <string, IActor>(); _actorCollidingObjects = new WorldDictionary <IActor, List <MapObject> >(); _playerSpawnAreas = new List <Tuple <Vector, Layer> >(); _pathFinders = new Dictionary <Layer, Pathfinder>(); _mapItems = new List <MapItem>(); this.Name = descriptor.Name; this.Bounds = descriptor.Bounds; this.Dimensions = descriptor.Dimensions; this.Dark = descriptor.Dark; this.TilesetPaths = descriptor.TilesetPaths; foreach (var layerDesc in descriptor.Layers) { Layer layer = new Layer(this, layerDesc); this.AddLayer(layerDesc.Name, layer); } // Look for spawnpoints foreach (var layer in this.Layers) { for (int x = 0; x < descriptor.Dimensions.X; x++) { for (int y = 0; y < descriptor.Dimensions.Y; y++) { if (layer.GetTile(x, y) != null && layer.GetTile(x, y).Attribute is PlayerSpawnTileAttribute) { this.AddPlayerStartArea(new Vector(x * Settings.TileSize, y * Settings.TileSize), layer); } } } } }
public static void Load(string fileName, List <MapDescriptor> mapDescriptors, IProgress <ProgressInfo> progress, CancellationToken ct) { var dir = Directory.GetParent(fileName).FullName; string[] lines = File.ReadAllLines(fileName); var p = 0; // how many ids are there? var maxId = 0; foreach (var line in lines) { string[] columns = line.Split(new[] { ',' }, 6); var i = int.Parse(columns[0].Trim()); if (i > maxId) { maxId = i; } } var tempMapDescriptors = new List <MapDescriptor>(); // add as many new map descriptors for (int i = 0; i < maxId + 1; i++) { var md = new MapDescriptor(); tempMapDescriptors.Add(md); if (i < mapDescriptors.Count) { md.set(mapDescriptors[i]); } } foreach (var line in lines) { string[] columns = line.Split(new[] { ',' }, 6); var i = int.Parse(columns[0].Trim()); var mapSet = sbyte.Parse(columns[1].Trim()); var zone = sbyte.Parse(columns[2].Trim()); var order = sbyte.Parse(columns[3].Trim()); var isPracticeBoard = bool.Parse(columns[4].Trim()); var mapDescriptorFilePath = columns[5].Trim(); tempMapDescriptors[i].MapSet = mapSet; tempMapDescriptors[i].Zone = zone; tempMapDescriptors[i].Order = order; tempMapDescriptors[i].IsPracticeBoard = isPracticeBoard; if (!string.IsNullOrEmpty(mapDescriptorFilePath)) { mapDescriptorFilePath = Path.Combine(dir, mapDescriptorFilePath); var importMd = PatchProcess.ImportMd(mapDescriptorFilePath, ProgressInfo.makeNoProgress(progress), ct); tempMapDescriptors[i].setFromImport(importMd); } progress?.Report(100 * p / lines.Count()); p++; } while (mapDescriptors.Count > tempMapDescriptors.Count) { mapDescriptors.RemoveAt(mapDescriptors.Count - 1); } for (int i = mapDescriptors.Count; i < tempMapDescriptors.Count; i++) { var md = new MapDescriptor(); // only add new maps, if there is a map descriptor file path available if (!string.IsNullOrEmpty(tempMapDescriptors[i].MapDescriptorFilePath)) { mapDescriptors.Add(md); } else { progress?.Report("Warning: Could not load the configuration after map " + i + " because the md files are not set."); break; } } for (int i = 0; i < mapDescriptors.Count; i++) { if (!tempMapDescriptors[i].Equals(mapDescriptors[i])) { tempMapDescriptors[i].Dirty = true; } mapDescriptors[i].setFromImport(tempMapDescriptors[i]); mapDescriptors[i].MapSet = tempMapDescriptors[i].MapSet; mapDescriptors[i].Zone = tempMapDescriptors[i].Zone; mapDescriptors[i].Order = tempMapDescriptors[i].Order; mapDescriptors[i].IsPracticeBoard = tempMapDescriptors[i].IsPracticeBoard; } progress?.Report(100); progress?.Report("Loaded configuration from " + fileName); }
public void ReadXElement_Empty_ThrowsArgumentNullException() { MapDescriptor mapDescriptor = new MapDescriptor(); XElement element = null; mapDescriptor.ReadXElement(element); }
/// <summary>Given a position and a map descriptor, creates that map at said position.</summary> void InstantiateMap(MapDescriptor descriptor, Vector3 position = default(Vector3)) { var tiles = descriptor.tiles; var tileSize = Game.instance.tileSize; // Find empty gameobject to keep map in, to keep our scene hierarchy in order var mapContainer = GameObject.Find("Map").transform; position -= new Vector3(tiles.GetLength(0), tiles.GetLength(1)) * tileSize * 0.5f; // TEMP: also make a note of the map bounds, for player movement Game.instance.mapBoundsMin = position; Game.instance.mapBoundsMax = position + new Vector3(tiles.GetLength(0) - 1, tiles.GetLength(1) - 1) * tileSize; for (var x = 0; x < tiles.GetLength(0); ++x) { for (var y = 0; y < tiles.GetLength(1); ++y) { // Place tile var tileToPlace = floorPrefab; var tilePosition = position + new Vector3(x, y) * tileSize; // Wait, is the tile a wall? if (tiles[x, y] == TileType.Wall) { // Yes. Find edges, place edge sprites on them tileToPlace = wallPrefab; if ((x > 0) && (tiles[x - 1, y] == TileType.Floor)) { var edge = Instantiate(edgePrefab, tilePosition, Quaternion.Euler(0, 0, 180)) as Transform; edge.parent = mapContainer; } if ((y > 0) && (tiles[x, y - 1] == TileType.Floor)) { var edge = Instantiate(edgePrefab, tilePosition, Quaternion.Euler(0, 0, 270)) as Transform; edge.parent = mapContainer; } if ((x < tiles.GetLength(0) - 1) && (tiles[x + 1, y] == TileType.Floor)) { var edge = Instantiate(edgePrefab, tilePosition, Quaternion.identity) as Transform; edge.parent = mapContainer; } if ((y < tiles.GetLength(1) - 1) && (tiles[x, y + 1] == TileType.Floor)) { var edge = Instantiate(edgePrefab, tilePosition, Quaternion.Euler(0, 0, 90)) as Transform; edge.parent = mapContainer; } } var tile = Instantiate(tileToPlace, tilePosition, Quaternion.identity) as Transform; tile.parent = mapContainer; // Also place visualization of grid cell var cell = Instantiate(gridPrefab, tilePosition, Quaternion.identity) as Transform; cell.parent = mapContainer; } } // Place goal at end goal.transform.position = position + new Vector3(tiles.GetLength(0) - 1, tiles.GetLength(1) - 1) * tileSize; // TEMP: place the player at the start position. This is kinda bad encapsulation, and needlessly constrains SEO var playerPos = Game.instance.player.transform.position; playerPos = position + new Vector3(descriptor.startX * tileSize, descriptor.startY * tileSize); Game.instance.player.transform.position = playerPos; Game.instance.player.startPosition = playerPos; Game.instance.player.Reset(); // why is this necessary? Assets.Scripts.Enemy.Instance.Initiate(playerPos); }
private void FetchImageFromWeb(MapDescriptor descriptor) { if (descriptor.ZoomLevel == initialZoomLevel) { if (AutomaticallyDownloadMaps) webAccessor.FetchAndSaveImageInNewThread(descriptor); } }
// building an easy map - only up and right turns. EasyMap gets a two dimensional array // and builds an easy map in it. the number 0 represents a wall (or solid matter) // and the number 1 represents a room (the path, a hallway, air, what ever you want) static MapDescriptor EasyMap(int sizeX, int sizeY) { System.Random rng = new System.Random(); var tiles = new TileType[sizeX, sizeY]; //finding the greatest common divisor of the lengths of the rectangle. // this gives a better way of randomizing tiles, instead in a ratio of 1:1 // the ratio depends on the size of the rectangle (for a 10 by 20 rectangle // the randomizing ratio for up and right will be 1:2) int gcd = FindGCD(tiles.GetLength(1), tiles.GetLength(0)); int ChanceNum = (tiles.GetLength(1) / gcd) + (tiles.GetLength(0) / gcd); // setting the whole tiles to 0, everything is a wall for (int i = 0; i < tiles.GetLength(0); i++) { for (int j = 0; j < tiles.GetLength(1); j++) { tiles[i,j] = TileType.Wall; } } //[0,0] is the starting point and so it always equals to 1. [0,0] represents the // right bottom point of the map tiles[0, 0] = TileType.Floor; //indexes to the last tile that was changed int CurrentRow = 0; int CurrentCol = 0; int num; // the pathway can be as long as the sum of the number of columns // and rows in the array minus 1 for (int i = 0; i < (tiles.GetLength(0) + tiles.GetLength(1)); i++) { if (CurrentCol < tiles.GetLength(1) - 1 && CurrentRow < tiles.GetLength(0) - 1) { //getting a random number between 0 and the chance num, so the odds //of getting an up or right turn will be adjusted by the size of the rectangle num = rng.Next(0, ChanceNum); if (num < Math.Min((tiles.GetLength(1) / gcd), (tiles.GetLength(0) / gcd))) { if(tiles.GetLength(1)>tiles.GetLength(0)){ CurrentRow++; tiles[CurrentRow, CurrentCol] = TileType.Floor; } else { CurrentCol++; tiles[CurrentRow, CurrentCol] = TileType.Floor; } } else{ if(tiles.GetLength(1)>tiles.GetLength(0)) { CurrentCol++; tiles[CurrentRow, CurrentCol] = TileType.Floor; }else { CurrentRow++; tiles[CurrentRow, CurrentCol] = TileType.Floor; } } } } while (CurrentRow != tiles.GetLength(0) - 1) { num = rng.Next(0, tiles.GetLength(1)); MoveUp(num, tiles); CurrentRow++; } while (CurrentCol != tiles.GetLength(1) - 1) { num = rng.Next(0, tiles.GetLength(0)); MoveRight(num, tiles); CurrentCol++; } var result = new MapDescriptor(); result.tiles = tiles; // Simple paths always start at the bottom left, end at the top right result.startX = 0; result.startY = 0; result.endX = sizeX; result.endY = sizeY; return result; }
private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (e != null && e.RowIndex < dataGridView1.Rows.Count) { var editedRow = dataGridView1.Rows[e.RowIndex] as DataGridViewRow; var editedMd = editedRow.DataBoundItem as MapDescriptor; if (!editedMd.Equals(editMd)) { editedMd.Dirty = true; } } BindingSource bs = dataGridView1.DataSource as BindingSource; if (bs.Count > 42) { buttonRemoveMap.Enabled = true; } else { buttonRemoveMap.Enabled = false; } clearValidationIssues(); List <MapDescriptor> mapDescriptors = (List <MapDescriptor>)((BindingSource)dataGridView1.DataSource).List; bool atLeastOneDirty = false; foreach (var md in mapDescriptors) { if (md.Dirty) { atLeastOneDirty = true; } } buttonSaveConfiguration.Enabled = atLeastOneDirty; var validation = MapDescriptor.getPracticeBoards(mapDescriptors, out _, out _); if (!validation.Passed) { addValidationIssues(validation); } var categories = new Dictionary <int, int>(); validation = MapDescriptor.getMapSets(mapDescriptors, out categories); if (validation.Passed) { foreach (int category in categories.Values.Distinct()) { var zones = new Dictionary <int, int>(); validation = MapDescriptor.getZones(mapDescriptors, category, out zones); if (validation.Passed) { foreach (int zone in zones.Values.Distinct()) { var ordering = new Dictionary <int, int>(); validation = MapDescriptor.getOrdering(mapDescriptors, category, zone, out ordering); if (!validation.Passed) { addValidationIssues(validation); } } } else { addValidationIssues(validation); } } } else { addValidationIssues(validation); } }
private Shape GenerateShapeFromFile(MapDescriptor desc) { long time = Environment.TickCount; int logDelta = (int)Math.Log(desc.Delta, 2.0) - EarthTiles.MinLogDelta; Shape shape = null; try { string filename = ShapeHGTFactory.CalculateFilenameFromLatLong(new LatLong(desc.Latitude,desc.Longitude)); using (System.IO.Stream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open)) { shapeFactory.Stream = stream; shape = shapeFactory.ReadAndReduceShapeFromFile(logDelta); } } catch (System.IO.FileNotFoundException) { shape = shapeFactory.GenerateNullShape(); } return shape; }
private Image GetImageFromSource(LatLong bottomLeftLocation, int desiredZoomLevel, int logDelta, out int actualZoomLevel) { actualZoomLevel = desiredZoomLevel; int imageDelta = CalculateLogDeltaFromZoom(desiredZoomLevel); LatLong centreLocation = CalculateCentreLocation(bottomLeftLocation, imageDelta); MapDescriptor d = new MapDescriptor(centreLocation.Latitude, centreLocation.Longitude, desiredZoomLevel); Image image = GetImageFromFile(d); if (image == null) { FetchImageFromWeb(d); return RecursivelyGetTiledImage(bottomLeftLocation, desiredZoomLevel - 1, logDelta, out actualZoomLevel); } return image; }
void setMap(MapDescriptor map) { this.currentMap = map; }
void createMap(MapDescriptor map) { setMap(map); new MapLoader().CreateWorld(map, this, portals, cam, transform); }
public static void ExportMd(string destination, string cachePath, MapDescriptor mapDescriptor, bool overwrite, IProgress <ProgressInfo> progress, CancellationToken ct) { var cacheFileSet = new DataFileSet(cachePath); if (Directory.Exists(destination) || string.IsNullOrEmpty(Path.GetExtension(destination))) { destination = Path.Combine(destination, mapDescriptor.InternalName + ".md"); } var directory = Path.GetDirectoryName(destination); if (!string.IsNullOrWhiteSpace(directory)) { Directory.CreateDirectory(directory); } string fileNameMd = destination; string fileNameFrb1 = Path.Combine(directory, mapDescriptor.FrbFile1 + ".frb"); string fileNameFrb2 = null; string fileNameFrb3 = null; string fileNameFrb4 = null; if (!string.IsNullOrWhiteSpace(mapDescriptor.FrbFile2)) { fileNameFrb2 = Path.Combine(directory, mapDescriptor.FrbFile2 + ".frb"); } if (!string.IsNullOrWhiteSpace(mapDescriptor.FrbFile3)) { fileNameFrb3 = Path.Combine(directory, mapDescriptor.FrbFile3 + ".frb"); } if (!string.IsNullOrWhiteSpace(mapDescriptor.FrbFile4)) { fileNameFrb4 = Path.Combine(directory, mapDescriptor.FrbFile4 + ".frb"); } string filesToBeReplacedMsg = ""; var filesToBeReplaced = new List <string>(); if (File.Exists(fileNameMd)) { filesToBeReplacedMsg += fileNameMd + "\n"; filesToBeReplaced.Add(fileNameMd); } if (File.Exists(fileNameFrb1)) { filesToBeReplacedMsg += fileNameFrb1 + "\n"; filesToBeReplaced.Add(fileNameFrb1); } if (fileNameFrb2 != null && File.Exists(fileNameFrb2)) { filesToBeReplacedMsg += fileNameFrb2 + "\n"; filesToBeReplaced.Add(fileNameFrb2); } if (fileNameFrb3 != null && File.Exists(fileNameFrb3)) { filesToBeReplacedMsg += fileNameFrb3 + "\n"; filesToBeReplaced.Add(fileNameFrb3); } if (fileNameFrb4 != null && File.Exists(fileNameFrb4)) { filesToBeReplacedMsg += fileNameFrb4 + "\n"; filesToBeReplaced.Add(fileNameFrb4); } if (filesToBeReplaced.Any()) { if (overwrite) { if (File.Exists(fileNameMd)) { File.Delete(fileNameMd); } if (File.Exists(fileNameFrb1)) { File.Delete(fileNameFrb1); } if (fileNameFrb2 != null && File.Exists(fileNameFrb2)) { File.Delete(fileNameFrb2); } if (fileNameFrb3 != null && File.Exists(fileNameFrb3)) { File.Delete(fileNameFrb3); } if (fileNameFrb4 != null && File.Exists(fileNameFrb4)) { File.Delete(fileNameFrb4); } } else { throw new FileAlreadyExistException("The following files already exist:\n" + filesToBeReplacedMsg, filesToBeReplaced.ToArray()); } } using (FileStream fs = File.Create(fileNameMd)) { byte[] content = Encoding.UTF8.GetBytes(mapDescriptor.ToMD()); fs.Write(content, 0, content.Length); } progress?.Report(new ProgressInfo(50, "Generated " + fileNameMd)); File.Copy(Path.Combine(cacheFileSet.param_folder, mapDescriptor.FrbFile1 + ".frb"), fileNameFrb1); progress?.Report("Extracted " + fileNameFrb1); if (fileNameFrb2 != null) { File.Copy(Path.Combine(cacheFileSet.param_folder, mapDescriptor.FrbFile2 + ".frb"), fileNameFrb2); progress?.Report("Extracted " + fileNameFrb2); } if (fileNameFrb3 != null) { File.Copy(Path.Combine(cacheFileSet.param_folder, mapDescriptor.FrbFile3 + ".frb"), fileNameFrb3); progress?.Report("Extracted " + fileNameFrb3); } if (fileNameFrb4 != null) { File.Copy(Path.Combine(cacheFileSet.param_folder, mapDescriptor.FrbFile4 + ".frb"), fileNameFrb4); progress?.Report("Extracted " + fileNameFrb4); } progress?.Report(100); }
bool tryGetMap(string mapName, out MapDescriptor descriptor) { return(mapBuffer.TryGetValue(mapName, out descriptor)); }
void Start() { MapDescriptor desc = ReadMap(); BuildMap(desc); }
public void RetrieveOrUpdateMapTerrain(CombinedMapData newMap) { MapDescriptor md = new MapDescriptor( newMap.BottomLeftLocation.Latitude, newMap.BottomLeftLocation.Longitude, newMap.ZoomLevel, newMap.ShapeDelta); if(previouslyCreatedTerrain.ContainsKey(md)) { newMap.CopyShapeFrom(previouslyCreatedTerrain[md]); FireMapUpdateCompletedEvent(new ShapeChangeEventArgs(newMap, ShapeChangeEventArgs.ChangeAction.Add)); } else { UpdateMapTerrain(newMap); } }
public CombinedMapData(CombinedMapData copy) : this() { desc = new MapDescriptor(copy.BottomLeftLocation.Latitude, copy.BottomLeftLocation.Longitude, copy.ZoomLevel, copy.ShapeDelta); this.TextureIndex = copy.TextureIndex; }