Created
August 23, 2012 13:21
-
-
Save frr149/3436544 to your computer and use it in GitHub Desktop.
Mandelbrot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(void)generateImageOfSize:(CGSize)imageSize | |
{ | |
// Determine integer size of image | |
NSInteger imageIntWidth = ceilf(imageSize.width); | |
NSInteger imageIntHeight = ceilf(imageSize.height); | |
// Determine coordinate maxima | |
assert(zoomFactor > 0.0f); | |
float coordMaxX = coordMinX + imageIntWidth / zoomFactor; | |
float coordMaxY = coordMinY + imageIntHeight / zoomFactor; | |
float deltaX = (coordMaxX - coordMinX) / imageIntWidth; | |
float deltaY = (coordMaxY - coordMinY) / imageIntHeight; | |
// Create image buffer | |
NSInteger nx = imageIntWidth; | |
NSInteger ny = imageIntHeight; | |
UInt8 *imageBuffer = malloc(nx * ny * 3 * sizeof(UInt8)); | |
// Fill buffer using Mandelbrot calculation | |
float logMaxIterations = log(MBMaxMandelbrotIterations); | |
NSUInteger ix, iy; | |
for ( ix = 0; ix < nx; ix++ ) { | |
float cReal = coordMinX + ix * deltaX; | |
for ( iy = 0; iy < ny; iy++ ) { | |
float cImag = coordMinY + iy * deltaY; | |
// Perform Mandelbrot iterations to see if point leads to escape | |
NSUInteger iterationIndex; | |
float zReal = 0.0f; | |
float zImag = 0.0f; | |
float zRealNew; | |
for( iterationIndex = 0; iterationIndex < MBMaxMandelbrotIterations && | |
fabs(zReal) < MBEscapeDistance && fabs(zImag) < MBEscapeDistance; iterationIndex++ ) { | |
zRealNew = (zReal * zReal) - (zImag * zImag) + cReal; | |
zImag = (2.0 * zReal * zImag ) + cImag; | |
zReal = zRealNew; | |
} | |
// Determine corresponding color and store in buffer | |
float logIterations = log(iterationIndex); | |
float depthRatio = logIterations / logMaxIterations; | |
NSUInteger imageOffset = iy * nx * 3 + ix * 3; | |
imageBuffer[imageOffset] = 255 * (1.0f - depthRatio); | |
imageBuffer[imageOffset+1] = 255 * (1.0f - depthRatio); | |
imageBuffer[imageOffset+2] = 255 * (1.0f - depthRatio); | |
} | |
} | |
// Create image from buffer | |
[self setImageForBuffer:imageBuffer pixelsX:nx pixelsY:ny]; | |
} | |
-(void)setImageForBuffer:(UInt8 *)buffer pixelsX:(NSUInteger)nx pixelsY:(NSUInteger)ny | |
{ | |
CGDataProviderRef provider = CGDataProviderCreateWithData( NULL, buffer, nx*ny*3, BrotMakerReleaseImageData ); | |
CGImageRef newImage = CGImageCreate( nx, ny, 8, 24, nx * 3, [[NSColorSpace genericRGBColorSpace] CGColorSpace], kCGBitmapByteOrderDefault, provider, NULL, NO, kCGRenderingIntentDefault ); | |
CGDataProviderRelease( provider ); | |
self.image = newImage; | |
CGImageRelease(image); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment