static void Main(string[] args) { if (args[4].Equals("*")) { args[4] = "0"; } SectorInfo sectorinfo = new SectorInfo() { RealMinimum = Convert.ToDouble(args[0]), ImgMinimum = Convert.ToDouble(args[1]), Delta = Convert.ToDouble(args[2]), FromX = Convert.ToInt32(args[3]), FromY = Convert.ToInt32(args[4]), Width = Convert.ToInt32(args[5]), Height = Convert.ToInt32(args[6]), MaxIterations = Convert.ToInt32(args[7]), MaxValue = Convert.ToInt32(args[8]) }; Calculator calculator = new Calculator(); Sector sector = calculator.CalculateSector(sectorinfo); SectorSerializer serializer = new SectorSerializer(); string filename = string.Format("{0}-{1}-{2}-{3}-{4}.bin", args[9], sectorinfo.FromX, sectorinfo.FromY, sectorinfo.Width, sectorinfo.Height); serializer.Serialize(sector, filename); }
public void PostSectorInfo(SectorInfo sectorInfo) { CloudQueueClient queueStorage = this.account.CreateCloudQueueClient(); CloudQueue queue = queueStorage.GetQueueReference("fractaltoprocess"); queue.AddMessage(this.SectorInfoToMessage(sectorInfo)); }
private void Calculate() { Bitmap bitmap = new Bitmap(pcbFractal.Width, pcbFractal.Height); pcbFractal.Image = bitmap; pcbFractal.Refresh(); realWidth = realDelta * pcbFractal.Width; imgHeight = imgDelta * pcbFractal.Height; realMin = realCenter - realWidth / 2; imgMin = imgCenter - imgHeight / 2; int width = pcbFractal.Width; int height = pcbFractal.Height; SectorInfo sectorinfo = new SectorInfo() { FromX = 0, FromY = 0, Width = width, Height = height, RealMinimum = realMin, ImgMinimum = imgMin, Delta = realDelta, MaxIterations = colors.Length, MaxValue = 4 }; Calculator calculator = new Calculator(); Sector sector = calculator.CalculateSector(sectorinfo); this.DrawValues(sector.FromX, sector.FromY, sector.Width, sector.Height, sector.Values); }
public override void Setup(SectorInfo sector, TerrainVerticesDatabase vertDatabase, Transform parent) { base.Setup(sector, vertDatabase, parent); List <TerrainVertData> verts = sector.GetTerrainVerts(vertDatabase); List <Vector3> points = new List <Vector3> (); foreach (TerrainVertData point in verts) { if (point.inlandPosition >= inlandRange.x && point.inlandPosition <= inlandRange.y) { points.Add(point.GetSurfacePos() - parent.transform.position); } } int quantity = (int)Random.Range(amount.x, amount.y); for (int i = 0; i < quantity; i++) { GameObject spawn = Instantiate(objectsToSpawn[Random.Range(0, objectsToSpawn.Length)], parent); spawn.name = objectsToSpawn[0].name; spawn.transform.localPosition = offset + points[Random.Range(0, points.Count)]; spawn.transform.localRotation = Quaternion.AngleAxis(Random.Range(0.0f, 360.0f), spawn.transform.up); } }
// Transforms p from World space into Texture space protected Vector2D WorldToTex(Vector2D p, SectorInfo s) { p += offset; p = p.GetRotated(rotation + s.rotation); p += s.offset; p *= scale * s.scale; return(p); }
static void Main(string[] args) { using (MPI.Environment environment = new MPI.Environment(ref args)) { if (args[4].Equals("*")) { args[4] = "0"; } SectorInfo sectorinfo = new SectorInfo() { RealMinimum = Convert.ToDouble(args[0]), ImgMinimum = Convert.ToDouble(args[1]), Delta = Convert.ToDouble(args[2]), FromX = Convert.ToInt32(args[3]), FromY = Convert.ToInt32(args[4]), Width = Convert.ToInt32(args[5]), Height = Convert.ToInt32(args[6]), MaxIterations = Convert.ToInt32(args[7]), MaxValue = Convert.ToInt32(args[8]) }; Intracommunicator comm = Communicator.world; if (comm.Rank == 0) { SectorInfo[] sectors = new SectorInfo[comm.Size]; for (int k = 0; k < sectors.Length; k++) { SectorInfo newsector = new SectorInfo() { RealMinimum = sectorinfo.RealMinimum, ImgMinimum = sectorinfo.ImgMinimum, Delta = sectorinfo.Delta, FromX = sectorinfo.FromX, FromY = sectorinfo.FromY + k * (sectorinfo.Height / comm.Size), Width = sectorinfo.Width, Height = sectorinfo.Height / comm.Size, MaxIterations = sectorinfo.MaxIterations, MaxValue = sectorinfo.MaxValue }; sectors[k] = newsector; } SectorInfo si = comm.Scatter(sectors); CalculateSector(args, si); } else { SectorInfo si = comm.Scatter <SectorInfo>(0); CalculateSector(args, si); } } }
// Transforms p from Texture space into World space protected Vector2D TexToWorld(Vector2D p, SectorInfo s) { p /= scale * s.scale; Vector2D soffset = s.offset.GetRotated(rotation); p -= soffset; p = p.GetRotated(-(rotation + s.rotation)); p -= offset; return(p); }
private static void CalculateSector(string[] args, SectorInfo sectorinfo) { Calculator calculator = new Calculator(); Sector sector = calculator.CalculateSector(sectorinfo); SectorSerializer serializer = new SectorSerializer(); string filename = string.Format("{0}-{1}-{2}-{3}-{4}.bin", args[9], sectorinfo.FromX, sectorinfo.FromY, sectorinfo.Width, sectorinfo.Height); serializer.Serialize(sector, filename); }
public void GenerateSectorsContent(List <SectorInfo> sectors, TerrainVerticesDatabase vertDatabase) { RandomSample rndSample = new RandomSample(sectors.Count); foreach (SectorArrangement sectorType in sectorTypes) { int rndIndex = rndSample.Next(); SectorInfo sectorInfo = sectors[rndIndex]; sectorType.Setup(sectorInfo, vertDatabase, sectorInfo.gameObject.transform); } }
public override void Setup(SectorInfo sector, TerrainVerticesDatabase vertDatabase, Transform parent) { base.Setup(sector, vertDatabase, parent); TerrainVertData vertData = vertDatabase.GetNearestVertData(parent.position); Vector3 spawnPos = vertData.GetSurfacePos() - parent.position; GameObject spawn = Instantiate(objectToSpawn, childOfLevel ? parent : null); spawn.name = objectToSpawn.name; spawn.transform.localPosition = offset + (childOfLevel ? spawnPos : parent.position); }
private static void Main(string[] args) { // Get the server info and display StarNet.ServerInfo serverInfo = StarNet.GetServerInfo(Address, Port); Console.WriteLine("Server: [Version: {0}, Players: {1}/{2}]", serverInfo.Version, serverInfo.PlayerCount, serverInfo.MaxPlayers); // Execute the /status command as a raw command and desplay string[] response = StarNet.ExecuteAdminCommand(Address, Port, Password, "/status"); Console.WriteLine(); Console.WriteLine("Raw command: /status"); using (var writer = new StreamWriter("Output.txt")) { foreach (var line in response) { Console.WriteLine(line); writer.WriteLine(line); } } Console.WriteLine(); Console.WriteLine(); // Create a session using (var session = StarNet.CreateSession(Address, Port, Password)) { // Get the player list and display var playerList = session.PlayerList(); Console.WriteLine("Players:"); foreach (var player in playerList) { Console.Write(player + ", "); } Console.WriteLine(); Console.WriteLine(); // Test player info for Koderz var playerInfo = session.PlayerInfo("Koderz"); Console.WriteLine(playerInfo); // Test server status var serverStatus = session.Status(); Console.WriteLine("Players [{0}/{1}] Memory(Free/Taken/Total)[{2}, {3}, {4}]", serverStatus.CurrentPlayers, serverStatus.MaxPlayers, serverStatus.MemoryFree, serverStatus.MemoryTaken, serverStatus.MemoryTotal); SectorInfo sectorInfo = session.GetSectorInfo(5, 5, 40); Console.WriteLine("EntityCount: {0} Astronauts: {1}", sectorInfo.Entities.Length, sectorInfo.Astronauts.Length); EntityInfoExtended entityInfo = session.GetEntityInfo(EntityType.SpaceStation, "SpawnStation"); Console.WriteLine("RealName: " + entityInfo.RealName + " BlockCount: " + entityInfo.BlockCount); } Console.ReadLine(); }
public SectInfo(uint version, string[] sectorUcs) { Version = version; NumSectors = (ushort)(sectorUcs.Length / 2); Sectors = new SectorInfo[NumSectors]; for (int i = 0; i < NumSectors; i++) { Sectors[i] = new SectorInfo(); Sectors[i].SectorCode = sectorUcs[i * 2]; Sectors[i].Ucs = Byte.Parse(sectorUcs[(i * 2) + 1]); } }
void Awake() { Planet currentPlanet = PlayerStatController.instance.currentPlanet; List <SectorTileInfo> planetTileInfoList = null; if (currentPlanet != null) { planetTileInfoList = TileController.instance.GetTileInfoListForPlanet(currentPlanet); } if (planetTileInfoList != null) { tileList = new List <SectorTile>(new SectorTile[width * height]); for (int x = 0; x < width; x++) { for (int z = 0; z < height; z++) { GameObject newTile = CreateTile(x, z); //Set tileList from singleton values to the new tile SectorTileInfo savedTile = planetTileInfoList[z * height + x]; if (savedTile.hasSector) { SectorInfo sectorInfo = newTile.AddComponent <SectorInfo>(); sectorInfo.sector = planetTileInfoList[z * height + x].sector; newTile.GetComponent <SectorTile>().sector = sectorInfo; } //Set tileList to attach to the gameobject tileList[z * height + x] = newTile.GetComponent <SectorTile>(); } } } else { tileList = new List <SectorTile>(new SectorTile[width * height]); for (int x = 0; x < width; x++) { for (int z = 0; z < height; z++) { GameObject newTile = CreateTile(x, z); tileList[z * height + x] = newTile.GetComponent <SectorTile>(); } } } }
private CloudQueueMessage SectorInfoToMessage(SectorInfo sectorInfo) { string value = string.Format( "SectorInfo {0} {1} {2} {3} {4} {5} {6} {7} {8}", sectorInfo.RealMinimum, sectorInfo.ImgMinimum, sectorInfo.Delta, sectorInfo.FromX, sectorInfo.FromY, sectorInfo.Width, sectorInfo.Height, sectorInfo.MaxIterations, sectorInfo.MaxValue ); return(new CloudQueueMessage(value)); }
/// <summary> /// Lista los sectores de una zona y por ciudad. /// </summary> /// <returns></returns> public List <SectorInfo> ListxZona(string CodCiudad, string CodZona) { db.SetParameterValue(commandSector, "i_operation", 'S'); db.SetParameterValue(commandSector, "i_option", 'B'); db.SetParameterValue(commandSector, "i_codciudad", CodCiudad); db.SetParameterValue(commandSector, "i_zona", CodZona); List <SectorInfo> col = new List <SectorInfo>(); IDataReader dr = null; SectorInfo m = null; try { dr = db.ExecuteReader(commandSector); while (dr.Read()) { m = Factory.GetSector(dr); col.Add(m); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("NIVI Error: {0} , NameSpace: {1}, Clase: {2}, Metodo: {3} ", ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Namespace, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name)); bool rethrow = ExceptionPolicy.HandleException(ex, "DataAccess Policy"); if (rethrow) { throw; } } finally { if (dr != null) { dr.Close(); } } return(col); }
// This restores all sectors to original values private void RestoreSectors() { int index = 0; foreach (Sector s in selection) { SectorInfo si = sectorinfo[index]; s.Fields.BeforeFieldsChange(); s.Fields[RotationName] = new UniValue(UniversalType.AngleDegreesFloat, Angle2D.RadToDeg(si.rotation)); s.Fields[XScaleName] = new UniValue(UniversalType.Float, si.scale.x); s.Fields[YScaleName] = new UniValue(UniversalType.Float, si.scale.y); s.Fields[XOffsetName] = new UniValue(UniversalType.Float, si.offset.x); s.Fields[YOffsetName] = new UniValue(UniversalType.Float, -si.offset.y); s.UpdateNeeded = true; s.UpdateCache(); index++; } }
public static CloudQueueMessage FromSectorInfoToMessage(SectorInfo sectorInfo) { string value = string.Format(CultureInfo.InvariantCulture, "SectorInfo {0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", sectorInfo.Id, sectorInfo.FromX, sectorInfo.FromY, sectorInfo.Width, sectorInfo.Height, sectorInfo.RealMinimum, sectorInfo.ImgMinimum, sectorInfo.Delta, sectorInfo.MaxIterations, sectorInfo.MaxValue ); return(new CloudQueueMessage(value)); }
public static SectorInfo FromMessageToSectorInfo(CloudQueueMessage msg) { string[] parameters = msg.AsString.Split(' '); SectorInfo value = new SectorInfo() { Id = new Guid(parameters[1]), FromX = Int32.Parse(parameters[2], CultureInfo.InvariantCulture), FromY = Int32.Parse(parameters[3], CultureInfo.InvariantCulture), Width = Int32.Parse(parameters[4], CultureInfo.InvariantCulture), Height = Int32.Parse(parameters[5], CultureInfo.InvariantCulture), RealMinimum = Double.Parse(parameters[6], CultureInfo.InvariantCulture), ImgMinimum = Double.Parse(parameters[7], CultureInfo.InvariantCulture), Delta = Double.Parse(parameters[8], CultureInfo.InvariantCulture), MaxIterations = Int32.Parse(parameters[9], CultureInfo.InvariantCulture), MaxValue = Int32.Parse(parameters[10], CultureInfo.InvariantCulture) }; return(value); }
private void EndLevel() { if (_levelEnded) { return; } _levelEnded = true; if (SectorManager.instance != null) { _lastSectorInfo = SectorManager.instance.CurrentSectorInfo; } ChangeLevelTime(LevelTime.NightEnd); if (levelEnded != null) { levelEnded(); } }
private void Awake() { if (instance != null && instance != this) { Destroy(this.gameObject); return; } else { instance = this; } Application.targetFrameRate = 60; Cursor.visible = false; _cursorRenderer = cursorObj.GetComponent <Image>(); cursorRect = cursorObj.GetComponent <RectTransform>(); CurrentDayInfo = new DayInfo(); CurrentDayInfo.day = 0; CurrentDayInfo.time = LevelTime.DayStart; _lastSectorInfo = null; }
void SpliceTerritory(List <MapRegion> zones) { sectors.Clear(); GameObject territories = new GameObject("Territories"); territories.transform.parent = transform; territories.transform.localPosition = Vector3.zero; territories.transform.localRotation = Quaternion.identity; int zoneCount = 1; foreach (MapRegion zone in zones) { SectorInfo sector = new SectorInfo(); sector.id = zoneCount; sector.offset = zone.GetCentre() * islandData.tileSize; sector.gameObject = AddChildMesh("Zone " + sector.id, territories.transform); sector.gameObject.transform.localPosition = sector.offset; sector.gameObject.GetComponent <MeshFilter> ().mesh = meshGen.GenerateZoneMesh(zone, sector, islandData.tileSize, vertDatabase); sector.gameObject.GetComponent <MeshRenderer> ().material = islandData.invisibleMaterial; if (debug) { sector.gameObject.GetComponent <MeshRenderer> ().material.color = randCol[(zoneCount % 20)]; } cakeslice.Outline outlineComponent = sector.gameObject.AddComponent <cakeslice.Outline> (); outlineComponent.color = zoneCount % 3; sectors.Add(sector); zoneCount++; } territories.AddComponent <CycleRegionOutline> (); }
public Mesh GenerateZoneMesh(MapRegion region, SectorInfo sector, float squareSize, TerrainVerticesDatabase vertDatabase) { squareGrid = new SquareGrid(region, squareSize); vertices.Clear(); triangles.Clear(); for (int x = 0; x < squareGrid.squares.GetLength(0); x++) { for (int y = 0; y < squareGrid.squares.GetLength(1); y++) { TriangulateSquare(squareGrid.squares[x, y]); } } vertDatabase.SetVerticesSector(vertices, transform.position + sector.offset, sector.id); Mesh regionMesh = new Mesh(); regionMesh.vertices = vertices.ToArray(); regionMesh.triangles = triangles.ToArray(); regionMesh.RecalculateNormals(); return(regionMesh); }
public ActionResult Create([Bind(Include = "Id,SectorName,SectorCode,Status")] SectorInfo sector) { using (var dbTransaction = _db.Database.BeginTransaction()) { try { ModelState.Clear(); sector.SectorId = string.Format("BI-{0:000000}", _db.SectorInfos.Count() + 1); sector.EntryBy = _db.Users.First(x => x.UserName == User.Identity.Name).Id; sector.EntryDate = DateTime.Now; TryValidateModel(sector); if (ModelState.IsValid) { _db.SectorInfos.Add(sector); _db.SaveChanges(); dbTransaction.Commit(); TempData["Toastr"] = Toastr.Added; return(RedirectToAction("Index")); } dbTransaction.Rollback(); return(View(sector)); } catch (Exception ex) { dbTransaction.Rollback(); TempData["Toastr"] = Toastr.DbError(ex.Message); return(RedirectToAction("Index")); } finally { ViewBag.Status = Common.ToSelectList <Status>(); } } }
void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; // If object is hit by mouse if (Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(0)) { GameObject hitObject = hit.collider.gameObject; if (LayerMask.LayerToName(hitObject.layer) == "Sectors") { SectorInfo sectorInfo = hitObject.GetComponent <SectorInfo>(); if (selectedSector != null) { previousSelectedSectorObject = selectedSectorObject; previousSector = selectedSector; previousSelectedSectorObject.GetComponent <MeshRenderer>().material = previousSector.sectorModelPrefab.GetComponent <MeshRenderer>().sharedMaterial; } selectedSectorObject = hitObject; selectedSector = sectorInfo.sector; selectedSectorObject.GetComponent <MeshRenderer>().material = selectedSectorMaterial; } else { if (selectedSector != null) { selectedSectorObject.GetComponent <MeshRenderer>().material = selectedSector.sectorModelPrefab.GetComponent <MeshRenderer>().sharedMaterial; } selectedSectorObject = null; selectedSector = null; } } }
public override void Run() { // This is a sample worker implementation. Replace with your logic. Trace.WriteLine("FractalWorkerRole entry point called", "Information"); CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); CloudBlobClient blobClient = account.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference("fractalsectors"); blobContainer.CreateIfNotExist(); QueueUtilities qutil = new QueueUtilities(account); CloudQueue queue = qutil.CreateQueueIfNotExists("fractaltoprocess"); CloudQueue outqueue = qutil.CreateQueueIfNotExists("fractalsectors"); Calculator calculator = new Calculator(); while (true) { CloudQueueMessage msg = queue.GetMessage(); if (msg != null) { Trace.WriteLine(string.Format("Processing {0}", msg.AsString)); SectorInfo info = SectorUtilities.FromMessageToSectorInfo(msg); if (info.Width > 100 || info.Height > 100) { Trace.WriteLine("Splitting message..."); for (int x = 0; x < info.Width; x += 100) { for (int y = 0; y < info.Height; y += 100) { SectorInfo newinfo = info.Clone(); newinfo.FromX = x + info.FromX; newinfo.FromY = y + info.FromY; newinfo.Width = Math.Min(100, info.Width - x); newinfo.Height = Math.Min(100, info.Height - y); CloudQueueMessage newmsg = SectorUtilities.FromSectorInfoToMessage(newinfo); queue.AddMessage(newmsg); } } } else { Trace.WriteLine("Processing message..."); Sector sector = calculator.CalculateSector(info); string blobname = string.Format("{0}.{1}.{2}.{3}.{4}", info.Id, sector.FromX, sector.FromY, sector.Width, sector.Height); CloudBlob blob = blobContainer.GetBlobReference(blobname); MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); foreach (int value in sector.Values) { writer.Write(value); } writer.Flush(); stream.Seek(0, SeekOrigin.Begin); blob.UploadFromStream(stream); stream.Close(); CloudQueueMessage outmsg = new CloudQueueMessage(blobname); outqueue.AddMessage(outmsg); } queue.DeleteMessage(msg); } else { Thread.Sleep(10000); Trace.WriteLine("Working", "Information"); } } }
public ActionResult BatchUpload(HttpPostedFileBase sectorFile) { using (var scope = new TransactionScope()) { try { var affectedRows = 0; var sectors = new List <SectorInfo>(); if (sectorFile == null || sectorFile.ContentLength <= 0) { TempData["Toastr"] = Toastr.CustomError("Invalid File!", "File is empty or corrupted."); return(RedirectToAction("Index")); } // 1048567 bytes = 1 MegaByte if (sectorFile.FileName == string.Empty || sectorFile.ContentLength > 1048576) { TempData["Toastr"] = Toastr.CustomError("Large File!", "File cannot be more than 1 MegaByte."); return(RedirectToAction("Index")); } var extension = Path.GetExtension(sectorFile.FileName); // ReSharper disable once InvertIf if (extension == null || _allowedUploadFile.IndexOf(extension) == -1) { TempData["Toastr"] = Toastr.CustomError("Invalid File!", "Unsupported file, only .xls, .xlsx, .csv file are allowed."); return(RedirectToAction("Index")); } // File reading begin with following format // +--------------+--------------+--------+ // | Airport Name | Airport Code | Status | // | xcxcxcxcxcxc | codecxcxcxcc | 0/1 | if (extension == ".csv") { using (var reader = new BinaryReader(sectorFile.InputStream)) { var binData = reader.ReadBytes(sectorFile.ContentLength); var result = System.Text.Encoding.UTF8.GetString(binData); var rows = result.Split('\n'); var rowNumber = 0; foreach (var row in rows) { if (rowNumber < 1) { rowNumber++; continue; } if (string.IsNullOrWhiteSpace(row.Trim())) { continue; } var cells = row.Trim().Replace("\r", "").Split(','); var sector = new SectorInfo { SectorName = cells[0].ToUpper().Trim(), SectorCode = cells[1].ToUpper().Trim(), Status = cells[2].Trim() == "Active" ? Status.Active : Status.Inactive, EntryBy = _db.Users.First(x => x.UserName == User.Identity.Name).Id, EntryDate = DateTime.Now }; if (_db.SectorInfos.Any(x => x.SectorName == sector.SectorName && x.SectorCode == sector.SectorCode)) { continue; } sector.SectorId = string.Format("BI-{0:000000}", _db.SectorInfos.Count() + 1); sectors.Add(sector); } } } else { using (var stream = sectorFile.InputStream) { IExcelDataReader reader; switch (extension) { case ".xls": reader = ExcelReaderFactory.CreateBinaryReader(stream); break; case ".xlsx": reader = ExcelReaderFactory.CreateOpenXmlReader(stream); break; default: reader = ExcelReaderFactory.CreateOpenXmlReader(stream); break; } var isHeading = true; while (reader != null && reader.Read()) { //skip heading from excel file if (isHeading) { isHeading = false; continue; } var sector = new SectorInfo { SectorName = reader.GetString(0).ToUpper().Trim(), SectorCode = reader.GetString(1).ToUpper().Trim(), Status = reader.GetString(2) == "Active" ? Status.Active : Status.Inactive, EntryBy = _db.Users.First(x => x.UserName == User.Identity.Name).Id, EntryDate = DateTime.Now }; if (_db.SectorInfos.Any(x => x.SectorName == sector.SectorName && x.SectorCode == sector.SectorCode)) { continue; } sector.SectorId = string.Format("BI-{0:000000}", _db.SectorInfos.Count() + 1); sectors.Add(sector); } } } foreach (var sector in sectors) { _db.SectorInfos.Add(sector); affectedRows += _db.SaveChanges(); //Sending Progress using SignalR Common.SendProgress("Uploading..", affectedRows, sectors.Count); } scope.Complete(); Thread.Sleep(1000); TempData["Toastr"] = Toastr.CustomSuccess(string.Format("Sector file uploaded successfully. {0} items added.", affectedRows)); return(RedirectToAction("Index")); } catch (Exception ex) { Transaction.Current.Rollback(); TempData["Toastr"] = Toastr.CustomError("Exception!", ex.Message); return(RedirectToAction("Index")); } } }
// Mode engages public override void OnEngage() { base.OnEngage(); // We don't want to record this for undoing while we move the geometry around. // This will be set back to normal when we're done. General.Map.UndoRedo.IgnorePropChanges = true; // Presentation renderer.SetPresentation(Presentation.Standard); // Selection General.Map.Map.ConvertSelection(SelectionType.Sectors); General.Map.Map.SelectionType = SelectionType.Sectors; if (General.Map.Map.SelectedSectorsCount == 0) { // Find the nearest linedef within highlight range Linedef l = General.Map.Map.NearestLinedef(mousemappos); if (l != null) { Sector selectsector = null; // Check on which side of the linedef the mouse is and which sector there is float side = l.SideOfLine(mousemappos); if ((side > 0) && (l.Back != null)) { selectsector = l.Back.Sector; } else if ((side <= 0) && (l.Front != null)) { selectsector = l.Front.Sector; } // Select the sector! if (selectsector != null) { selectsector.Selected = true; foreach (Sidedef sd in selectsector.Sidedefs) { sd.Line.Selected = true; } } } } // Get sector selection selection = General.Map.Map.GetSelectedSectors(true); if (selection.Count == 0) { General.Interface.MessageBeep(MessageBeepType.Default); General.Interface.DisplayStatus(StatusType.Action, "A selected sector is required for this action."); General.Editing.CancelMode(); return; } editsector = General.GetByIndex(selection, 0); // Get the texture texture = GetTexture(editsector); if ((texture == null) || (texture == General.Map.Data.WhiteTexture) || (texture.Width <= 0) || (texture.Height <= 0) || !texture.IsImageLoaded) { General.Interface.MessageBeep(MessageBeepType.Default); General.Interface.DisplayStatus(StatusType.Action, "The selected sector must have a loaded texture to align."); General.Editing.CancelMode(); return; } // Cache the transformation values sectorinfo = new List <SectorInfo>(selection.Count); foreach (Sector s in selection) { SectorInfo si; si.rotation = Angle2D.DegToRad(s.Fields.GetValue(RotationName, 0.0f)); si.scale.x = s.Fields.GetValue(XScaleName, 1.0f); si.scale.y = s.Fields.GetValue(YScaleName, 1.0f); si.offset.x = s.Fields.GetValue(XOffsetName, 0.0f); si.offset.y = -s.Fields.GetValue(YOffsetName, 0.0f); sectorinfo.Add(si); } // We want the texture corner nearest to the center of the sector Vector2D fp; fp.x = (editsector.BBox.Left + editsector.BBox.Right) / 2; fp.y = (editsector.BBox.Top + editsector.BBox.Bottom) / 2; // Transform the point into texture space fp = WorldToTex(fp); // Snap to the nearest left-top corner fp.x = (float)Math.Floor(fp.x / texture.ScaledWidth) * texture.ScaledWidth; fp.y = (float)Math.Ceiling(fp.y / texture.ScaledHeight) * texture.ScaledHeight; // Now move the offset so that the 0,0 point is at this location // We want to work with the 0,0 location because it makes things easier. SectorInfo si0 = sectorinfo[0]; si0.offset -= fp / si0.scale; sectorinfo[0] = si0; UpdateRectangleComponents(); UpdateSectors(); }
public ActionResult Edit([Bind(Include = "Id,SectorName,SectorCode,Status")] SectorInfo sector, int?id) { using (var dbTransaction = _db.Database.BeginTransaction()) { try { if (id == null) { TempData["Toastr"] = Toastr.HttpNotFound; return(RedirectToAction("Index")); } if (_db.SectorInfos.Count(x => x.Id == id) < 1) { TempData["Toastr"] = Toastr.HttpNotFound; return(RedirectToAction("Index")); } var sectorInfo = _db.SectorInfos.Single(x => x.Id == id); if (sectorInfo == null) { TempData["Toastr"] = Toastr.HttpNotFound; return(RedirectToAction("Index")); } ModelState.Clear(); sector.SectorId = sectorInfo.SectorId; sector.EntryBy = sectorInfo.EntryBy; sector.EntryDate = sectorInfo.EntryDate; sector.DelStatus = sectorInfo.DelStatus; TryValidateModel(sector); if (!ModelState.IsValid) { return(View(sector)); } _db.SectorInfos .Where(x => x.Id == id) .Update(u => new SectorInfo { SectorName = sector.SectorName, SectorCode = sector.SectorCode, Status = sector.Status }); dbTransaction.Commit(); TempData["Toastr"] = Toastr.Updated; return(RedirectToAction("Index")); } catch (Exception ex) { dbTransaction.Rollback(); TempData["Toastr"] = Toastr.DbError(ex.Message); return(RedirectToAction("Index")); } finally { ViewBag.StatusList = Common.ToSelectList <Status>(sector.Status); } } }
public virtual void Setup(SectorInfo sector, TerrainVerticesDatabase vertDatabase, Transform parent) { }
public unsafe Dx11RenderingDrawingRoom(Dx11RenderingDevice device, Description description) { Device = device; TextureView = ((Dx11RenderingTextureAllocator)(description.TextureAllocator)).TextureView; TextureAllocator = description.TextureAllocator; Vector2 textureScaling = new Vector2(16777216.0f) / new Vector2(TextureAllocator.Size.X, TextureAllocator.Size.Y); RoomGeometry roomGeometry = description.Room.RoomGeometry; // Create buffer Vector3 worldPos = description.Room.WorldPos + description.Offset; int singleSidedVertexCount = roomGeometry.VertexPositions.Count; int vertexCount = VertexCount = singleSidedVertexCount + roomGeometry.DoubleSidedTriangleCount * 3; if (vertexCount == 0) { return; } VertexBufferSize = vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint) + sizeof(ulong) + sizeof(uint)); fixed(byte *data = new byte[VertexBufferSize]) { Vector3 *positions = (Vector3 *)(data); uint * colors = (uint *)(data + vertexCount * sizeof(Vector3)); uint * overlays = (uint *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint))); ulong * uvwAndBlendModes = (ulong *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint))); uint * editorUVAndSectorTexture = (uint *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint) + sizeof(ulong))); // Setup vertices for (int i = 0; i < singleSidedVertexCount; ++i) { positions[i] = roomGeometry.VertexPositions[i] + worldPos; } for (int i = 0; i < singleSidedVertexCount; ++i) { colors[i] = Dx11RenderingDevice.CompressColor(roomGeometry.VertexColors[i]); } for (int i = 0; i < singleSidedVertexCount; ++i) { Vector2 vertexEditorUv = roomGeometry.VertexEditorUVs[i]; uint editorUv = 0; editorUv |= (uint)((int)vertexEditorUv.X) & 3; editorUv |= ((uint)((int)vertexEditorUv.Y) & 3) << 2; editorUVAndSectorTexture[i] = editorUv; } { SectorInfo lastSectorInfo = new SectorInfo(-1, -1, BlockFace.Floor); uint lastSectorTexture = 0; uint overlay = 0; for (int i = 0, triangleCount = singleSidedVertexCount / 3; i < triangleCount; ++i) { SectorInfo currentSectorInfo = roomGeometry.TriangleSectorInfo[i]; if (!lastSectorInfo.Equals(currentSectorInfo)) { SectorTextureResult result = description.SectorTextureGet(description.Room, currentSectorInfo.Pos.X, currentSectorInfo.Pos.Y, currentSectorInfo.Face); lastSectorInfo = currentSectorInfo; lastSectorTexture = 0; if (result.SectorTexture != SectorTexture.None) { // Use sector texture lastSectorTexture = 0x40 | (((uint)result.SectorTexture - 1) << 8); } else { // Use sector color lastSectorTexture = (((uint)(result.Color.X * 255)) << 8) | (((uint)(result.Color.Y * 255)) << 16) | (((uint)(result.Color.Z * 255)) << 24); } // Highlight / dim sectors if (result.Highlighted) { lastSectorTexture |= 0x10; } if (result.Dimmed) { lastSectorTexture |= 0x20; } // Indicate selected textured faces if (result.Selected && roomGeometry.TriangleTextureAreas[i].Texture != null) { lastSectorTexture |= 0x80; } // Assign overlay color which will be used in geometry mode if face has service texture (e.g. arrows) overlay = Dx11RenderingDevice.CompressColor(new Vector3(result.Overlay.X, result.Overlay.Y, result.Overlay.Z), (result.Hidden ? 0.4f : 1.0f), false); } editorUVAndSectorTexture[i * 3 + 0] |= lastSectorTexture; editorUVAndSectorTexture[i * 3 + 1] |= lastSectorTexture; editorUVAndSectorTexture[i * 3 + 2] |= lastSectorTexture; overlays[i * 3 + 0] = overlay; overlays[i * 3 + 1] = overlay; overlays[i * 3 + 2] = overlay; } } RetryTexturing: ; { int doubleSidedVertexIndex = singleSidedVertexCount; for (int i = 0, triangleCount = singleSidedVertexCount / 3; i < triangleCount; ++i) { TextureArea texture = roomGeometry.TriangleTextureAreas[i]; if (texture.Texture == null) { // Render as geometry uvwAndBlendModes[i * 3 + 0] = 1ul << 24; uvwAndBlendModes[i * 3 + 1] = 1ul << 24; uvwAndBlendModes[i * 3 + 2] = 1ul << 24; } else if (texture.Texture is TextureInvisible) { // Render as invisible uvwAndBlendModes[i * 3 + 0] = 0ul << 24; uvwAndBlendModes[i * 3 + 1] = 0ul << 24; uvwAndBlendModes[i * 3 + 2] = 0ul << 24; } else { // Render as textured (the texture may turn out to be unavailable) if (texture.Texture.IsUnavailable) { // Texture is unvailable (i.e. file couldn't be loaded. ImageC image = Dx11RenderingDevice.TextureUnavailable; VectorInt3 position = TextureAllocator.Get(image); uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); } else if (texture.TriangleCoordsOutOfBounds) { // Texture is available but coordinates are ouf of bounds ImageC image = Dx11RenderingDevice.TextureCoordOutOfBounds; VectorInt3 position = TextureAllocator.Get(image); uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); } else if (!texture.ParentArea.IsZero && !texture.ParentArea.Intersects(texture.GetRect())) { // Texture is available but coordinates are ouf of bounds ImageC image = Dx11RenderingDevice.TextureCoordOutOfBounds; VectorInt3 position = TextureAllocator.Get(image); uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode); } else { // Texture is available VectorInt3 position = TextureAllocator.GetForTriangle(texture); uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord0, (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord1, (uint)texture.BlendMode); uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord2, (uint)texture.BlendMode); } // Duplicate double sided triangles if (texture.DoubleSided) { positions[doubleSidedVertexIndex] = positions[i * 3 + 2]; colors[doubleSidedVertexIndex] = colors[i * 3 + 2]; overlays[doubleSidedVertexIndex] = overlays[i * 3 + 2]; uvwAndBlendModes[doubleSidedVertexIndex] = uvwAndBlendModes[i * 3 + 2]; editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 2]; positions[doubleSidedVertexIndex] = positions[i * 3 + 1]; colors[doubleSidedVertexIndex] = colors[i * 3 + 1]; overlays[doubleSidedVertexIndex] = overlays[i * 3 + 1]; uvwAndBlendModes[doubleSidedVertexIndex] = uvwAndBlendModes[i * 3 + 1]; editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 1]; positions[doubleSidedVertexIndex] = positions[i * 3 + 0]; colors[doubleSidedVertexIndex] = colors[i * 3 + 0]; overlays[doubleSidedVertexIndex] = overlays[i * 3 + 0]; uvwAndBlendModes[doubleSidedVertexIndex] = uvwAndBlendModes[i * 3 + 0]; editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 0]; } } } if (doubleSidedVertexIndex != vertexCount) { throw new ArgumentException("Double sided triangle count of RoomGeometry is wrong!"); } // Retry texturing once at max if (TexturesInvalidated && !TexturesInvalidatedRetried) { TexturesInvalidatedRetried = true; goto RetryTexturing; } } // Create GPU resources VertexBuffer = new Buffer(device.Device, new IntPtr(data), new BufferDescription(VertexBufferSize, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); VertexBufferBindings = new VertexBufferBinding[] { new VertexBufferBinding(VertexBuffer, sizeof(Vector3), (int)((byte *)positions - data)), new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)colors - data)), new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)overlays - data)), new VertexBufferBinding(VertexBuffer, sizeof(ulong), (int)((byte *)uvwAndBlendModes - data)), new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)editorUVAndSectorTexture - data)) }; VertexBuffer.SetDebugName("Room " + (description.Room.Name ?? "")); } TextureAllocator.GarbageCollectionCollectEvent.Add(GarbageCollectTexture); }