private static IRenderStrategy GetFilter(string filter) { IRenderStrategy filterStrategy = null; switch (filter) { case "grayscale": filterStrategy = GrayscaleStrategy; break; case "sepia": filterStrategy = SepiaStrategy; break; default: if (Regex.IsMatch(filter, @"\Athreshold\(\d{1,3}\)\z")) { var threshold = Convert.ToInt32(Regex.Match(filter, @"\d{1,3}").Value); if (threshold >= 0 && threshold <= 100) { filterStrategy = new ThresholdStrategy(threshold); } } break; } return(filterStrategy); }
/// <summary> /// Creates a new <see cref="GLHardwareRenderer"/> that will use the specified <see cref="IRenderStrategy"/> /// to render the contents of the libretro core's framebuffer to the specified <see cref="IRenderContext"/>. /// </summary> /// <param name="renderStrategy">The render strategy to use to render to the <paramref name="frontendContext"/>.</param> /// <param name="frontendContext">The render context to render to.</param> public GLHardwareRenderer(IRenderStrategy renderStrategy, IRenderContext frontendContext) { // We can't reference the GetCurrentFramebuffer method from a field initializer, so need to set it here _getCurrentFramebufferDlgt = new retro_hw_get_current_framebuffer_t(GetCurrentFramebuffer); _renderStrategy = renderStrategy; _frontendContext = frontendContext; }
public ConsoleRegion(Point? start, Size? size, IRenderStrategy renderStrategy = null) { _renderStrategy = renderStrategy ?? new ProgressiveRenderStrategy(); _start = start.HasValue ? start.Value : new Point(0, 0); _size = ConsoleManager.MaxSize; if (size.HasValue) _size = _size.BestFitWithin(_start, size.Value); }
public Shape(string id, IRay ray, IRenderable renderable, IRenderStrategy renderer) { ID = id; Ray = ray; Renderable = renderable; Renderer = renderer; UIDispatcher.Invoke(() => { Polygon = Renderer.Render(Renderable, Ray); }); }
/// <summary> /// Renders the entire scene. /// </summary> /// <param name="doWaitForNextFame"><c>true</c>, if this method should wait to the correct frame start time /// before it renders, else <c>false</c>.</param> /// <returns><c>true</c>, if the caller should wait some milliseconds before rendering the next time.</returns> public static bool Render(bool doWaitForNextFame) { if (_device == null || !_deviceOk) { return(true); } IRenderStrategy renderStrategy = RenderStrategy; IRenderPipeline pipeline = RenderPipeline; renderStrategy.BeginRender(doWaitForNextFame); _renderAndResourceAccessLock.EnterReadLock(); bool doReset = false; try { Fire(DeviceSceneBegin); pipeline.BeginRender(); pipeline.Render(); pipeline.EndRender(); Fire(DeviceSceneEnd); _device.PresentEx(renderStrategy.PresentMode); Fire(DeviceScenePresented); ContentManager.Instance.Clean(); } catch (SharpDXException e) { doReset = true; DeviceState state = CheckDeviceState(); ServiceRegistration.Get <ILogger>().Warn("GraphicsDevice: DirectX Exception, DeviceState: {0}", e, state); _deviceOk = state == DeviceState.Ok; return(!_deviceOk); } finally { _renderAndResourceAccessLock.ExitReadLock(); // If there are exceptions during render pass, the device can stay in an invalid state, even if the CheckDeviceState returns "ok". // So we prefer to reset the device and try continue rendering. if (doReset) { Reset(); } } return(false); }
public MainPage() { this.InitializeComponent(); (App.ViewModel.NewCommand as CommandBase).ExecuteDelegate = e => _NewFile(); (App.ViewModel.OpenCommand as CommandBase).ExecuteDelegate = e => _OpenFile(); (App.ViewModel.SaveCommand as CommandBase).ExecuteDelegate = e => _SaveFile(); _ContextRenderer = new RenderStrategy(); this.DataContext = App.ViewModel; }
private static IRenderStrategy InstanciateStrategy(Options options) { IRenderStrategy strat = null; switch (options.Strategy) { case Strategy.Dataflow: default: strat = new DataFlowStrategy <Bitmap>(new SystemDrawing()); break; } return(strat); }
private static IRenderStrategy InstanciateStrategy(Options options) { IRenderStrategy strat = null; switch (options.Strategy) { case Strategy.Dataflow: default: //strat = new DataFlowStrategy<SKBitmap>(new Maploader.Renderer.Imaging.SkiaSharp()); strat = new DataFlowStrategy <Bitmap>(new Maploader.Renderer.Imaging.SystemDrawing()); break; } return(strat); }
/// <summary> /// Renders the entire scene. /// </summary> /// <param name="doWaitForNextFame"><c>true</c>, if this method should wait to the correct frame start time /// before it renders, else <c>false</c>.</param> /// <returns><c>true</c>, if the caller should wait some milliseconds before rendering the next time.</returns> public static bool Render(bool doWaitForNextFame) { if (_device == null || !_deviceOk) { return(true); } IRenderStrategy renderStrategy = RenderStrategy; IRenderPipeline pipeline = RenderPipeline; renderStrategy.BeginRender(doWaitForNextFame); _renderAndResourceAccessLock.EnterReadLock(); try { Fire(DeviceSceneBegin); pipeline.BeginRender(); pipeline.Render(); pipeline.EndRender(); Fire(DeviceSceneEnd); _device.PresentEx(renderStrategy.PresentMode); Fire(DeviceScenePresented); ContentManager.Instance.Clean(); } catch (SharpDXException e) { DeviceState state = CheckDeviceState(); ServiceRegistration.Get <ILogger>().Warn("GraphicsDevice: DirectX Exception, DeviceState: {0}", e, state); _deviceOk = state == DeviceState.Ok; return(!_deviceOk); } finally { _renderAndResourceAccessLock.ExitReadLock(); } return(false); }
private static void ConfigureStrategy(IRenderStrategy strat, Options options, HashSet <LevelDbWorldKey2> allSubChunks, int extendedDia, int zoom, World world, Dictionary <string, Texture> textures, int tileSize, int chunkSize, int zmin, int zmax, int xmin, int xmax) { strat.RenderSettings = new RenderSettings() { RenderCoordinateStrings = options.RenderCoords, RenderMode = options.RenderMode, MaxNumberOfThreads = options.MaxNumberOfThreads, MaxNumberOfQueueEntries = options.MaxNumberOfQueueEntries, YMax = options.LimitY, BrillouinJ = options.BrillouinJ, BrillouinDivider = options.BrillouinDivider, BrillouinOffset = options.BrillouinOffset, TrimCeiling = options.TrimCeiling, Profile = options.Profile, }; strat.ForceOverwrite = options.ForceOverwrite; strat.AllWorldKeys = allSubChunks; strat.InitialDiameter = extendedDia; strat.InitialZoomLevel = (int)zoom; strat.World = world; strat.TotalChunkCount = _totalChunk; strat.TexturePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "textures"); strat.TextureDictionary = textures; strat.OutputPath = options.OutputPath; strat.TileSize = tileSize; strat.ChunksPerDimension = options.ChunksPerDimension; strat.ChunkSize = chunkSize; strat.ZMin = zmin; strat.ZMax = zmax; strat.XMin = xmin; strat.XMax = xmax; strat.ChunksRendered += RenderDisplay; strat.ZoomLevelRenderd += RenderZoom; strat.FileFormat = options.FileFormat; strat.FileQuality = options.Quality; strat.Dimension = options.Dimension; strat.Profile = options.Profile; strat.DeleteExistingUpdateFolder = options.DeleteExistingUpdateFolder; }
static int Main(string[] args) { _time = Stopwatch.StartNew(); var options = new Options(); Parser.Default.ParseArguments <Options>(args).WithParsed(o => { options = o; options.Loaded = true; }); if (!options.Loaded) { return(-1); } // Parameter Validation try { if (options.LimitX != null) { var splittedLimit = options.LimitX.Split(',').Select(x => Convert.ToInt32(x)).OrderBy(x => x).ToArray(); if (splittedLimit.Length != 2) { throw new ArgumentOutOfRangeException("LimitX"); } options.LimitXLow = splittedLimit[0]; options.LimitXHigh = splittedLimit[1]; } } catch (Exception) { Console.WriteLine($"The value '{options.LimitX}' for the LimitZ parameter is not valid. Try something like -10,10"); return(-1); } try { if (options.LimitZ != null) { var splittedLimit = options.LimitZ.Split(',').Select(x => Convert.ToInt32(x)).OrderBy(x => x).ToArray(); if (splittedLimit.Length != 2) { throw new ArgumentOutOfRangeException("LimitZ"); } options.LimitZLow = splittedLimit[0]; options.LimitZHigh = splittedLimit[1]; } } catch (Exception) { Console.WriteLine($"The value '{options.LimitZ}' for the LimitZ parameter is not valid. Try something like -10,10"); return(-1); } var world = new World(); try { Console.WriteLine("Opening world..."); world.Open(options.MinecraftWorld); } catch (Exception ex) { Console.WriteLine($"Could not open world at '{options.MinecraftWorld}'!. Did you specify the .../db folder?"); Console.WriteLine("The reason was:"); Console.WriteLine(ex.Message); return(-1); } // Start Generation int xmin = 0; int xmax = 0; int zmin = 0; int zmax = 0; HashSet <UInt64> hashedCoordinateKeys = null; if (options.LimitXLow.HasValue && options.LimitXHigh.HasValue && options.LimitZHigh.HasValue && options.LimitZLow.HasValue) { _totalChunk = (options.LimitXHigh.Value - options.LimitXLow.Value + 1) * (options.LimitZHigh.Value - options.LimitZLow.Value + 1); } else { Console.WriteLine("Generating a list of all chunk keys in the database.\nThis could take a few minutes"); var keys = world.ChunkKeys.ToHashSet(); unchecked { hashedCoordinateKeys = keys.Select(x => Coordinate2D.CreateHashKey(x.X, x.Y)).ToHashSet(); } _totalChunk = keys.Count; Console.WriteLine($"Total Chunk count {keys.Count}"); Console.WriteLine(); xmin = keys.Min(x => x.X); xmax = keys.Max(x => x.X); zmin = keys.Min(x => x.Y); zmax = keys.Max(x => x.Y); Console.WriteLine($"The total dimensions of the map are"); Console.WriteLine($" X: {xmin} to {xmax}"); Console.WriteLine($" Z: {zmin} to {zmax}"); Console.WriteLine(); } if (options.LimitXLow.HasValue && options.LimitXHigh.HasValue) { xmin = options.LimitXLow.Value; xmax = options.LimitXHigh.Value; Console.WriteLine($"Limiting X to {xmin} to {xmax}"); } if (options.LimitZLow.HasValue && options.LimitZHigh.HasValue) { zmin = options.LimitZLow.Value; zmax = options.LimitZHigh.Value; Console.WriteLine($"Limiting Z to {zmin} to {zmax}"); } if (options.LimitY > 0) { Console.WriteLine($"Limiting Y to {options.LimitY}"); } Console.WriteLine("Reading terrain_texture.json..."); var json = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"textures", "terrain_texture.json")); var ts = new TerrainTextureJsonParser(json, ""); var textures = ts.Textures; Console.WriteLine(); const int chunkSize = 256; int chunksPerDimension = 2; int tileSize = chunkSize * chunksPerDimension; var maxDiameter = Math.Max(Math.Abs(xmax - xmin + 1), Math.Abs(zmax - zmin + 1)); Console.WriteLine($"The maximum diameter of the map is {maxDiameter}"); maxDiameter = (maxDiameter + (chunksPerDimension - 1)) / chunksPerDimension; Console.WriteLine($"For {chunksPerDimension} chunks per tile, new max diameter is {maxDiameter}"); var zoom = (int)(Math.Ceiling(Math.Log(maxDiameter) / Math.Log(2))); int extendedDia = (int)Math.Pow(2, zoom); Console.WriteLine($"To generate the zoom levels, we expand the diameter to {extendedDia}"); Console.WriteLine($"This results in {zoom+1} zoom levels"); List <Exception> exes = new List <Exception>(); IRenderStrategy strat = null; switch (options.Strategy) { case Strategy.ParallelFor: strat = new ParallelForRenderStrategy(); break; case Strategy.SingleFor: strat = new SingleForRenderStrategy(); break; default: strat = new SingleForRenderStrategy(); break; } strat.RenderSettings = new RenderSettings() { RenderCoords = options.RenderCoords, RenderMode = options.RenderMode, MaxNumberOfThreads = options.MaxNumberOfThreads, Keys = hashedCoordinateKeys, YMax = options.LimitY, BrillouinJ = options.BrillouinJ, BrillouinDivider = options.BrillouinDivider }; strat.InitialDiameter = extendedDia; strat.InitialZoomLevel = (int)zoom; strat.World = world; strat.TotalChunkCount = _totalChunk; strat.TexturePath = Path.Combine(Environment.CurrentDirectory, "textures"); strat.TextureDictionary = textures; strat.OutputPath = options.OutputPath; strat.TileSize = tileSize; strat.ChunksPerDimension = chunksPerDimension; strat.ChunkSize = chunkSize; strat.ZMin = zmin; strat.ZMax = zmax; strat.XMin = xmin; strat.XMax = xmax; strat.ChunksRendered += RenderDisplay; strat.RenderInitialLevel(); var missingTextures = strat.MissingTextures; File.WriteAllLines("missingtextures.txt", missingTextures.Distinct()); strat.ZoomLevelRenderd += RenderZoom; strat.RenderZoomLevels(); try { var mapHtml = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "map.thtml")); mapHtml = mapHtml.Replace("%maxnativezoom%", zoom.ToString()); mapHtml = mapHtml.Replace("%maxzoom%", (zoom + 2).ToString()); mapHtml = mapHtml.Replace("%tilesize%", (tileSize).ToString()); mapHtml = mapHtml.Replace("%factor%", (Math.Pow(2, zoom - 4)).ToString()); File.WriteAllText(Path.Combine(options.OutputPath, options.MapHtml), mapHtml); } catch (Exception ex) { Console.WriteLine("Could not write map.html"); Console.WriteLine(ex.Message); } world.Close(); Console.WriteLine("Total Time {0}", _time.Elapsed); return(0); }
/// <summary> /// Crops and renders image using <see cref="IRenderStrategy"/> /// </summary> /// <param name="bitmap">Source image</param> /// <param name="croppingArea">Crop region</param> /// <param name="strategy">Renders strategy</param> /// <returns>Resulted image</returns> public async Task <Bitmap> RenderBitmap(Bitmap bitmap, Rectangle croppingArea, IRenderStrategy strategy) { return(await strategy.Process(bitmap, croppingArea)); }
/// <summary> /// Applies filter on PNG image in body of HTTP request /// </summary> /// <param name="filter">Name of the filter</param> /// <param name="coords">Cropping area of image</param> public void Post(string filter, string coords) { Bitmap bodyBitmap = null; Bitmap result = null; MemoryStream stream = null; try { IRenderStrategy filterStrategy = GetFilter(filter); if (Context.Request.ContentLength64 > 102400 || Context.Request.ContentLength64 <= 8 || filterStrategy == null) { Context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } byte[] file = new byte[Context.Request.ContentLength64]; Context.Request.InputStream.Read(file, 0, 8); for (int i = 0; i < 8; i++) { if (file[i] != PngSignature[i]) { Context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } } Context.Request.InputStream.Read(file, 8, (int)Context.Request.ContentLength64 - 8); stream = new MemoryStream(file); Renderer.Renderer renderer = new Renderer.Renderer(); bodyBitmap = new Bitmap(stream); Rectangle cropArea = ConvertToRectangle(coords); cropArea.Intersect(new Rectangle(0, 0, bodyBitmap.Width, bodyBitmap.Height)); logger.Trace($"#{Context.Request.RequestTraceIdentifier} Rectangle of target bitmap: {cropArea.X}, {cropArea.Y}, {cropArea.Width}, {cropArea.Height}"); if (cropArea.Width == 0 || cropArea.Height == 0) { Context.Response.StatusCode = (int)HttpStatusCode.NoContent; return; } result = renderer.RenderBitmap(bodyBitmap, cropArea, filterStrategy).Result; stream.Dispose(); stream = new MemoryStream(); result.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Context.Response.AddHeader("Content-Type", "application/octet-stream"); Context.Response.ContentLength64 = stream.Length; Context.Response.OutputStream.Write(stream.ToArray(), 0, (int)stream.Length); } catch (OverflowException e) when(e.Message == "Value was either too large or too small for an Int32.") { Context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } catch (ArgumentException) { Context.Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } catch (Exception ex) { throw ex; } finally { if (bodyBitmap != null) { bodyBitmap.Dispose(); } if (result != null) { result.Dispose(); } if (stream != null) { stream.Dispose(); } } }
public static ConsoleRegion WholeWindow(IRenderStrategy renderStrategy = null) { return new ConsoleRegion(new Point(0, 0), ConsoleManager.MaxSize, renderStrategy); }
public ContentController(IRenderStrategy renderStrategy, IContentHandler contentHandler, ITemplateEngine templateEngine) { _renderStrategy = renderStrategy; _contentHandler = contentHandler; _templateEngine = templateEngine; }