#include <stdio.h>                                                 //李明谦
#include <complex.h>
#include <math.h>
#include<cv.h>
#include<highgui.h>
#include<cxcore.h>
#define IMAGE_SIZE 600

int eventMickey = -1, lx = -1, ly = -1, flagsMickey = -1;
IplImage *pImg;
double o = -2, p = -2;

double mSetTest (double a, double b)
{
    int i = 0;
    double d, e, f;
    double complex sum = 0.0 + 0.0 * I;
    double complex c = a + b * I;
    a = b = 0.0;
    while(1)
    {
        f = a * a - b * b;
        d = 2 * a * b;
        double complex sum = (f + d * I) + c;
        a = creal(sum);
        b = cimag(sum);
        e = sqrt(a * a + b * b);
        i++;
        if (i >= 200 && e <= 2.0)
        {
            return 0;
            break;
        }
        else if (e > 2.0)
        {
            return i;
            break;
        }
    }
}

void DrawingPicture (void)
{
    int ret, i, j;
    double a, b;
    for (i = 0;i <= IMAGE_SIZE - 1;i++)
    {
        a = ((double)1/150) * i + o;
        for (j = 0;j <= IMAGE_SIZE - 1;j++)
        {
            b = ((double)1/150) * j + p;
            ret = mSetTest(a, b);
            CvScalar sca;
            if (ret == 0)
            {
                sca.val[0]=0;
                sca.val[1]=0;
                sca.val[2]=255;
                cvSet2D(pImg,j,i,sca);
            }
            else
            {
                sca.val[0]=0;
                sca.val[1]=255;
                sca.val[2]=0;
                cvSet2D(pImg,j,i,sca);
            }
        }
    cvShowImage("mandelbrot", pImg);
    }
}

void on_mouse( int event, int x, int y, int flags,void* param)
{
    switch (event)
    {
        case CV_EVENT_LBUTTONDOWN:
        {
            eventMickey = event;
            lx = x;
            ly = y;
            flagsMickey = flags;
            o += (lx-IMAGE_SIZE/2.0) * (double)1/150,p += (ly-IMAGE_SIZE/2.0) * (double)1/150;
            DrawingPicture ();
            break;
        }
    }
}

int main()
{
    pImg = cvCreateImage(/*size*/cvSize(IMAGE_SIZE, IMAGE_SIZE), /*depth*/ 8, /*nChannels*/3);
    cvNamedWindow(/*name of the window*/"mandelbrot", 1);
    DrawingPicture ();
    cvSetMouseCallback("mandelbrot",on_mouse,0);
    cvWaitKey(/*delay*/0);

    cvDestroyWindow("mandelbrot");
    //cvRelease(&pImg);
    return 0;
    cvDestroyWindow("mandelbrot");
    //cvRelease(&pImg);
    return 0;
}

