Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Linq;
- using System.Text;
- namespace SpecialOlympics.Mandelbrot
- {
- class Program
- {
- interface IFractalPalette<out TColor>
- {
- TColor ColorOf(int iteration);
- }
- interface IFractalImageGenerator<out TColor>
- {
- TColor[,] Generate();
- }
- class SimpleBlackAndWhitePallete : IFractalPalette<Color>
- {
- private readonly int _maxIterations;
- public SimpleBlackAndWhitePallete(int maxIterations)
- {
- _maxIterations = maxIterations;
- }
- public Color ColorOf(int iteration)
- {
- return iteration == _maxIterations ? Color.Black : Color.White;
- }
- }
- class MandelbrotGenerator<TColor> : IFractalImageGenerator<TColor>
- {
- protected readonly int _height;
- protected readonly int _width;
- protected readonly Tuple<float, float> _xDimensions;
- protected readonly Tuple<float, float> _yDimensions;
- protected readonly int _maxIterations;
- protected readonly IFractalPalette<TColor> _palette;
- public MandelbrotGenerator(Tuple<float, float> xDimensions, Tuple<float, float> yDimensions, int height, int width, int maxIterations, IFractalPalette<TColor> palette)
- {
- _xDimensions = xDimensions;
- _yDimensions = yDimensions;
- _height = height;
- _width = width;
- _maxIterations = maxIterations;
- _palette = palette;
- }
- private TColor ComputeColor(int pixelX, int pixelY)
- {
- var x0 = _xDimensions.Item1 + (pixelX / (float)_width) * (_xDimensions.Item2 - _xDimensions.Item1);
- var y0 = _yDimensions.Item1 + (pixelY / (float)_height) * (_yDimensions.Item2 - _yDimensions.Item1);
- var x = 0.0;
- var y = 0.0;
- var iteration = 0;
- while (x*x + y*y < 2*2 && iteration < _maxIterations)
- {
- var xTemp = x*x - y*y + x0;
- y = 2*x*y + y0;
- x = xTemp;
- iteration++;
- }
- return _palette.ColorOf(iteration);
- }
- public virtual TColor[,] Generate()
- {
- var results = new TColor[_width, _height];
- for (var x = 0; x < _width; x++)
- {
- for (var y = 0; y < _height; y++)
- {
- results[x, y] = ComputeColor(x, y);
- }
- }
- return results;
- }
- }
- static void Main(string[] args)
- {
- using (var bitmap = new Bitmap(2048, 2048))
- {
- var pallete = new SimpleBlackAndWhitePallete(2000);
- var generator = new MandelbrotGenerator<Color>(new Tuple<float, float>(-2.5f, 1f),
- new Tuple<float, float>(-1.75f, 1.75f), bitmap.Width, bitmap.Height, 2000, pallete);
- var colors = generator.Generate();
- for (var i = 0; i < bitmap.Width; i++)
- {
- for (var j = 0; j < bitmap.Height; j++)
- {
- bitmap.SetPixel(i, j, colors[i, j]);
- }
- }
- bitmap.Save("mandelbrot.png", ImageFormat.Png);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment