mandelbrot.cpp
Go to the documentation of this file.
00001 // This file is part of Eigen, a lightweight C++ template library
00002 // for linear algebra.
00003 //
00004 // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
00005 //
00006 // Eigen is free software; you can redistribute it and/or
00007 // modify it under the terms of the GNU Lesser General Public
00008 // License as published by the Free Software Foundation; either
00009 // version 3 of the License, or (at your option) any later version.
00010 //
00011 // Alternatively, you can redistribute it and/or
00012 // modify it under the terms of the GNU General Public License as
00013 // published by the Free Software Foundation; either version 2 of
00014 // the License, or (at your option) any later version.
00015 //
00016 // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
00017 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00018 // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
00019 // GNU General Public License for more details.
00020 //
00021 // You should have received a copy of the GNU Lesser General Public
00022 // License and a copy of the GNU General Public License along with
00023 // Eigen. If not, see <http://www.gnu.org/licenses/>.
00024 
00025 #include "mandelbrot.h"
00026 #include <iostream>
00027 #include<QtGui/QPainter>
00028 #include<QtGui/QImage>
00029 #include<QtGui/QMouseEvent>
00030 #include<QtCore/QTime>
00031 
00032 void MandelbrotWidget::resizeEvent(QResizeEvent *)
00033 {
00034   if(size < width() * height())
00035   {
00036     std::cout << "reallocate buffer" << std::endl;
00037     size = width() * height();
00038     if(buffer) delete[]buffer;
00039     buffer = new unsigned char[4*size];
00040   }
00041 }
00042 
00043 template<typename T> struct iters_before_test { enum { ret = 8 }; };
00044 template<> struct iters_before_test<double> { enum { ret = 16 }; };
00045 
00046 template<typename Real> void MandelbrotThread::render(int img_width, int img_height)
00047 {
00048   enum { packetSize = Eigen::internal::packet_traits<Real>::size }; // number of reals in a Packet
00049   typedef Eigen::Array<Real, packetSize, 1> Packet; // wrap a Packet as a vector
00050 
00051   enum { iters_before_test = iters_before_test<Real>::ret };
00052   max_iter = (max_iter / iters_before_test) * iters_before_test;
00053   const int alignedWidth = (img_width/packetSize)*packetSize;
00054   unsigned char *const buffer = widget->buffer;
00055   const double xradius = widget->xradius;
00056   const double yradius = xradius * img_height / img_width;
00057   const int threadcount = widget->threadcount;
00058   typedef Eigen::Array<Real, 2, 1> Vector2;
00059   Vector2 start(widget->center.x() - widget->xradius, widget->center.y() - yradius);
00060   Vector2 step(2*widget->xradius/img_width, 2*yradius/img_height);
00061   total_iter = 0;
00062 
00063   for(int y = id; y < img_height; y += threadcount)
00064   {
00065     int pix = y * img_width;
00066 
00067     // for each pixel, we're going to do the iteration z := z^2 + c where z and c are complex numbers, 
00068     // starting with z = c = complex coord of the pixel. pzi and pzr denote the real and imaginary parts of z.
00069     // pci and pcr denote the real and imaginary parts of c.
00070 
00071     Packet pzi_start, pci_start;
00072     for(int i = 0; i < packetSize; i++) pzi_start[i] = pci_start[i] = start.y() + y * step.y();
00073 
00074     for(int x = 0; x < alignedWidth; x += packetSize, pix += packetSize)
00075     {
00076       Packet pcr, pci = pci_start, pzr, pzi = pzi_start, pzr_buf;
00077       for(int i = 0; i < packetSize; i++) pzr[i] = pcr[i] = start.x() + (x+i) * step.x();
00078 
00079       // do the iterations. Every iters_before_test iterations we check for divergence,
00080       // in which case we can stop iterating.
00081       int j = 0;
00082       typedef Eigen::Matrix<int, packetSize, 1> Packeti;
00083       Packeti pix_iter = Packeti::Zero(), // number of iteration per pixel in the packet
00084               pix_dont_diverge; // whether or not each pixel has already diverged
00085       do
00086       {
00087         for(int i = 0; i < iters_before_test/4; i++) // peel the inner loop by 4
00088         {
00089 #         define ITERATE \
00090             pzr_buf = pzr; \
00091             pzr = pzr.square(); \
00092             pzr -= pzi.square(); \
00093             pzr += pcr; \
00094             pzi = (2*pzr_buf)*pzi; \
00095             pzi += pci;
00096           ITERATE ITERATE ITERATE ITERATE
00097         }
00098         pix_dont_diverge = ((pzr.square() + pzi.square())
00099                            .eval() // temporary fix as what follows is not yet vectorized by Eigen
00100                            <= Packet::Constant(4))
00101                                 // the 4 here is not a magic value, it's a math fact that if
00102                                 // the square modulus is >4 then divergence is inevitable.
00103                            .template cast<int>();
00104         pix_iter += iters_before_test * pix_dont_diverge;
00105         j++;
00106         total_iter += iters_before_test * packetSize;
00107       }
00108       while(j < max_iter/iters_before_test && pix_dont_diverge.any()); // any() is not yet vectorized by Eigen
00109 
00110       // compute pixel colors
00111       for(int i = 0; i < packetSize; i++)
00112       {
00113         buffer[4*(pix+i)] = 255*pix_iter[i]/max_iter;
00114         buffer[4*(pix+i)+1] = 0;
00115         buffer[4*(pix+i)+2] = 0;
00116       }
00117     }
00118 
00119     // if the width is not a multiple of packetSize, fill the remainder in black
00120     for(int x = alignedWidth; x < img_width; x++, pix++)
00121       buffer[4*pix] = buffer[4*pix+1] = buffer[4*pix+2] = 0;
00122   }
00123   return;
00124 }
00125 
00126 void MandelbrotThread::run()
00127 {
00128   setTerminationEnabled(true);
00129   double resolution = widget->xradius*2/widget->width();
00130   max_iter = 128;
00131   if(resolution < 1e-4f) max_iter += 128 * ( - 4 - std::log10(resolution));
00132   int img_width = widget->width()/widget->draft;
00133   int img_height = widget->height()/widget->draft;
00134   single_precision = resolution > 1e-7f;
00135 
00136   if(single_precision)
00137     render<float>(img_width, img_height);
00138   else
00139     render<double>(img_width, img_height);
00140 }
00141 
00142 void MandelbrotWidget::paintEvent(QPaintEvent *)
00143 {
00144   static float max_speed = 0;
00145   long long total_iter = 0;
00146 
00147   QTime time;
00148   time.start();
00149   for(int th = 0; th < threadcount; th++)
00150     threads[th]->start(QThread::LowPriority);
00151   for(int th = 0; th < threadcount; th++)
00152   {
00153     threads[th]->wait();
00154     total_iter += threads[th]->total_iter;
00155   }
00156   int elapsed = time.elapsed();
00157 
00158   if(draft == 1)
00159   {
00160     float speed = elapsed ? float(total_iter)*1000/elapsed : 0;
00161     max_speed = std::max(max_speed, speed);
00162     std::cout << threadcount << " threads, "
00163               << elapsed << " ms, "
00164               << speed << " iters/s (max " << max_speed << ")" << std::endl;
00165     int packetSize = threads[0]->single_precision
00166                    ? int(Eigen::internal::packet_traits<float>::size)
00167                    : int(Eigen::internal::packet_traits<double>::size);
00168     setWindowTitle(QString("resolution ")+QString::number(xradius*2/width(), 'e', 2)
00169                   +QString(", %1 iterations per pixel, ").arg(threads[0]->max_iter)
00170                   +(threads[0]->single_precision ? QString("single ") : QString("double "))
00171                   +QString("precision, ")
00172                   +(packetSize==1 ? QString("no vectorization")
00173                                   : QString("vectorized (%1 per packet)").arg(packetSize)));
00174   }
00175   
00176   QImage image(buffer, width()/draft, height()/draft, QImage::Format_RGB32);
00177   QPainter painter(this);
00178   painter.drawImage(QPoint(0, 0), image.scaled(width(), height()));
00179 
00180   if(draft>1)
00181   {
00182     draft /= 2;
00183     setWindowTitle(QString("recomputing at 1/%1 resolution...").arg(draft));
00184     update();
00185   }
00186 }
00187 
00188 void MandelbrotWidget::mousePressEvent(QMouseEvent *event)
00189 {
00190   if( event->buttons() & Qt::LeftButton )
00191   {
00192     lastpos = event->pos();
00193     double yradius = xradius * height() / width();
00194     center = Eigen::Vector2d(center.x() + (event->pos().x() - width()/2) * xradius * 2 / width(),
00195                              center.y() + (event->pos().y() - height()/2) * yradius * 2 / height());
00196     draft = 16;
00197     for(int th = 0; th < threadcount; th++)
00198       threads[th]->terminate();
00199     update();
00200   }
00201 }
00202 
00203 void MandelbrotWidget::mouseMoveEvent(QMouseEvent *event)
00204 {
00205   QPoint delta = event->pos() - lastpos;
00206   lastpos = event->pos();
00207   if( event->buttons() & Qt::LeftButton )
00208   {
00209     double t = 1 + 5 * double(delta.y()) / height();
00210     if(t < 0.5) t = 0.5;
00211     if(t > 2) t = 2;
00212     xradius *= t;
00213     draft = 16;
00214     for(int th = 0; th < threadcount; th++)
00215       threads[th]->terminate();
00216     update();
00217   }
00218 }
00219 
00220 int main(int argc, char *argv[])
00221 {
00222   QApplication app(argc, argv);
00223   MandelbrotWidget w;
00224   w.show();
00225   return app.exec();
00226 }
00227 
00228 #include "mandelbrot.moc"


re_vision
Author(s): Dorian Galvez-Lopez
autogenerated on Sun Jan 5 2014 11:31:44