Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class FractalBase : MonoBehaviour {
- Texture2D texture;
- public int resolution = 128;
- public int maxIterations = 1000;
- public Gradient g;
- public GradientColorKey[] gck;
- public GradientAlphaKey[] gak;
- public float zoom = 1f;
- public float xShift = 0;
- public float yShift = 0;
- public float moveSens = 10;
- void Awake ()
- {
- texture = GetComponent<Texture2D>();
- }
- void Start()
- {
- texture = new Texture2D(resolution, resolution);
- texture.name = "MandelTexture";
- UpdateTexture();
- GetComponent<MeshRenderer>().material.mainTexture = texture;
- }
- void Update()
- {
- //navigation stuff
- if (Input.GetButtonDown("Fire1"))
- {
- float s = moveSens * zoom;
- Vector2 v2 = Input.mousePosition;
- xShift += (v2.x - Screen.width / 2) / s;
- yShift += (v2.y - Screen.height / 2) / s;
- texture = new Texture2D(resolution, resolution);
- UpdateTexture();
- GetComponent<MeshRenderer>().material.mainTexture = texture;
- }
- float z = Input.GetAxis("ZoomAxis");
- if (z != 0)
- {
- zoom += z * 10;
- texture = new Texture2D(resolution, resolution);
- UpdateTexture();
- GetComponent<MeshRenderer>().material.mainTexture = texture;
- }
- }
- void UpdateTexture()
- {
- for (int x = 0; x < resolution; x++)
- {
- for (int z = 0; z < resolution; z++)
- {
- //called for every pixel on the quad
- CalcMandelbrot(x, z);
- }
- }
- texture.Apply();
- }
- //where the magic happens
- void CalcMandelbrot(int row, int col)
- {
- float re = (((row - resolution / 2.0f) / zoom) + xShift) * 4.0f / resolution;
- float im = (((col - resolution / 2.0f) / zoom) + yShift) * 4.0f / resolution;
- float x = 0, y = 0;
- int iteration = 0;
- while (x*x + y*y <= 4 && iteration < maxIterations)
- {
- float x1 = x * x - y * y + re;
- y = 2 * x * y + im;
- x = x1;
- iteration++;
- }
- if (iteration < maxIterations)
- {
- texture.SetPixel(row, col, g.Evaluate((float)iteration / maxIterations));
- }
- else
- {
- texture.SetPixel(row, col, g.Evaluate(1));
- }
- }
- float Norm(Vector2 v2)
- {
- return v2.x * v2.x + v2.y * v2.y;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement