add julia set

This commit is contained in:
Yongwei Xing 2021-03-02 13:10:14 +08:00
parent c75fea7185
commit ca593e6a6e
2 changed files with 65 additions and 0 deletions

25
example/example_julia.go Normal file
View file

@ -0,0 +1,25 @@
package main
import (
"generativeart"
"math/rand"
"time"
)
func julia1(z complex128) complex128 {
c := complex(-0.1, 0.651)
z = z*z + c
return z
}
func main() {
rand.Seed(time.Now().Unix())
c := generativeart.NewCanva(800, 800, 1.5, 1.5)
c.SetIterations(800)
c.SetColorSchema(generativeart.Viridis)
c.FillBackground()
c.Draw(generativeart.NewJulia(julia1, 40))
c.ToPNG("julia.png")
}

40
julia.go Normal file
View file

@ -0,0 +1,40 @@
package generativeart
import "math/cmplx"
// GenFunc defines a func type used by julia set.
type GenFunc func(complex128) complex128
type julia struct {
fn GenFunc
maxz float64
}
func NewJulia(formula GenFunc, maxz float64) *julia {
return &julia{
fn: formula,
maxz: maxz,
}
}
// Generative draws a julia set.
func (j *julia)Generative(c *canva) {
n := len(c.opts.colorSchema)
if n > 255 {
n = 255
}
for i := 0; i <= c.width; i++ {
for k := 0; k <= c.height; k++ {
nit := 0
z := complex(float64(i)/float64(c.width)*2.0*c.yaixs-c.yaixs, float64(k)/float64(c.height)*2.0*c.yaixs-c.yaixs)
for cmplx.Abs(z) <= j.maxz && nit < c.opts.nIters {
z = j.fn(z)
nit += 1
}
idx := uint8(nit*255/c.opts.nIters) % uint8(n)
c.img.Set(i, k, c.opts.colorSchema[idx])
}
}
}