Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created December 12, 2019 18:03
Show Gist options
  • Save paulohrpinheiro/a76447eef5549f56ff12fbfbaa6ebd6d to your computer and use it in GitHub Desktop.
Save paulohrpinheiro/a76447eef5549f56ff12fbfbaa6ebd6d to your computer and use it in GitHub Desktop.
Mandelbrot Fractal draw
package main
import (
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
"sync"
)
const (
size = 1000
maxLoop = 5000
fileName = "mandel.png"
maxColors = 255
leftX = -2.0
rightX = 0.5
topY = 1.25
bottomY = -1.25
)
var (
wg sync.WaitGroup
)
func makePalette() []color.Color {
palette := make([]color.Color, maxColors)
for i := 0; i < maxColors-1; i++ {
palette[i] = color.RGBA{uint8(i/10), uint8(i%10), uint8(i), maxColors}
}
palette[maxColors-1] = palette[0]
return palette
}
func lifetime(x float64, y float64) int {
c := complex(x, y)
z := c
for i := 0; i < maxLoop; i++ {
if cmplx.Abs(z) > 2.0 {
return i
}
z = (z * z) + c
}
return maxLoop
}
func plotLine(img *image.Paletted, x int, convertedX, convertedY, factorY float64) {
defer wg.Done()
for y := 0; y < size; y++ {
paletteIndex := uint8(lifetime(convertedX, convertedY) % maxColors)
img.SetColorIndex(x, y, paletteIndex)
convertedY += factorY
}
}
func writeToFile(img *image.Paletted) {
f, createErr := os.Create(fileName)
if createErr != nil {
panic(createErr)
}
defer f.Close()
encodeErr := png.Encode(f, img)
if encodeErr != nil {
panic(encodeErr)
}
}
func main() {
palette := makePalette()
rect := image.Rect(0, 0, size, size)
img := image.NewPaletted(rect, palette)
factorX := (rightX - leftX) / float64(size)
factorY := (topY - bottomY) / float64(size)
convertedX := leftX
for x := 0; x < size; x++ {
convertedY := bottomY
wg.Add(1)
go plotLine(img, x, convertedX, convertedY, factorY)
convertedX += factorX
}
wg.Wait()
writeToFile(img)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment