Merge branch 'master' into blender2.8
[blender.git] / source / blender / freestyle / intern / application / Controller.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/freestyle/intern/application/Controller.cpp
22  *  \ingroup freestyle
23  */
24
25 extern "C" {
26 #include <Python.h>
27 }
28
29 #include <string>
30 #include <fstream>
31 #include <float.h>
32
33 #include "AppView.h"
34 #include "AppCanvas.h"
35 #include "AppConfig.h"
36 #include "Controller.h"
37
38 #include "../image/Image.h"
39
40 #include "../scene_graph/NodeDrawingStyle.h"
41 #include "../scene_graph/NodeShape.h"
42 #include "../scene_graph/NodeTransform.h"
43 #include "../scene_graph/NodeViewLayer.h"
44 #include "../scene_graph/ScenePrettyPrinter.h"
45 #include "../scene_graph/VertexRep.h"
46
47 #include "../stroke/PSStrokeRenderer.h"
48 #include "../stroke/TextStrokeRenderer.h"
49 #include "../stroke/StrokeTesselator.h"
50 #include "../stroke/StyleModule.h"
51
52 #include "../system/StringUtils.h"
53 #include "../system/PythonInterpreter.h"
54
55 #include "../view_map/SteerableViewMap.h"
56 #include "../view_map/ViewMap.h"
57 #include "../view_map/ViewMapIO.h"
58 #include "../view_map/ViewMapTesselator.h"
59
60 #include "../winged_edge/Curvature.h"
61 #include "../winged_edge/WEdge.h"
62 #include "../winged_edge/WingedEdgeBuilder.h"
63 #include "../winged_edge/WXEdgeBuilder.h"
64
65 #include "../blender_interface/BlenderFileLoader.h"
66 #include "../blender_interface/BlenderStrokeRenderer.h"
67 #include "../blender_interface/BlenderStyleModule.h"
68
69 #include "BKE_global.h"
70 #include "BLI_utildefines.h"
71 #include "BLI_path_util.h"
72
73 #include "DNA_freestyle_types.h"
74
75 #include "FRS_freestyle.h"
76
77 namespace Freestyle {
78
79 Controller::Controller()
80 {
81         const string sep(Config::DIR_SEP.c_str());
82 #if 0
83         const string filename = Config::Path::getInstance()->getHomeDir() + sep + Config::OPTIONS_DIR + sep +
84                                 Config::OPTIONS_CURRENT_DIRS_FILE;
85         _current_dirs = new ConfigIO(filename, Config::APPLICATION_NAME + "CurrentDirs", true);
86 #endif
87
88         _RootNode = new NodeGroup;
89         _RootNode->addRef();
90
91 #if 0
92         _SilhouetteNode = NULL;
93         _ProjectedSilhouette = NULL;
94         _VisibleProjectedSilhouette = NULL;
95
96         _DebugNode = new NodeGroup;
97         _DebugNode->addRef();
98 #endif
99
100         _winged_edge = NULL;
101
102         _pView = NULL;
103         _pRenderMonitor = NULL;
104
105         _edgeTesselationNature = (Nature::SILHOUETTE | Nature::BORDER | Nature::CREASE);
106
107         _ProgressBar = new ProgressBar;
108         _SceneNumFaces = 0;
109 #if 0
110         _minEdgeSize = DBL_MAX;
111 #endif
112         _EPSILON = 1.0e-6;
113         _bboxDiag = 0;
114
115         _ViewMap = 0;
116
117         _Canvas = 0;
118
119         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_traditional;
120         //_VisibilityAlgo = ViewMapBuilder::ray_casting;
121
122         _Canvas = new AppCanvas;
123
124         _inter = new PythonInterpreter();
125         _EnableViewMapCache = false;
126         _EnableQI = true;
127         _EnableFaceSmoothness = false;
128         _ComputeRidges = true;
129         _ComputeSteerableViewMap = false;
130         _ComputeSuggestive = true;
131         _ComputeMaterialBoundaries = true;
132         _sphereRadius = 1.0;
133         _creaseAngle = 134.43;
134         prevSceneHash = -1.0;
135
136         init_options();
137 }
138
139 Controller::~Controller()
140 {
141         if (NULL != _RootNode) {
142                 int ref = _RootNode->destroy();
143                 if (0 == ref)
144                         delete _RootNode;
145         }
146
147 #if 0
148         if (NULL != _SilhouetteNode) {
149                 int ref = _SilhouetteNode->destroy();
150                 if (0 == ref)
151                         delete _SilhouetteNode;
152         }
153
154         if (NULL != _DebugNode) {
155                 int ref = _DebugNode->destroy();
156                 if (0 == ref)
157                         delete _DebugNode;
158         }
159 #endif
160
161         if (_winged_edge) {
162                 delete _winged_edge;
163                 _winged_edge = NULL;
164         }
165
166         if (0 != _ViewMap) {
167                 delete _ViewMap;
168                 _ViewMap = 0;
169         }
170
171         if (0 != _Canvas) {
172                 delete _Canvas;
173                 _Canvas = 0;
174         }
175
176         if (_inter) {
177                 delete _inter;
178                 _inter = NULL;
179         }
180
181         if (_ProgressBar) {
182                 delete _ProgressBar;
183                 _ProgressBar = NULL;
184         }
185
186         //delete _current_dirs;
187 }
188
189 void Controller::setView(AppView *iView)
190 {
191         if (NULL == iView)
192                 return;
193
194         _pView = iView;
195         _Canvas->setViewer(_pView);
196 }
197
198 void Controller::setRenderMonitor(RenderMonitor *iRenderMonitor)
199 {
200         _pRenderMonitor = iRenderMonitor;
201 }
202
203 void Controller::setPassDiffuse(float *buf, int width, int height)
204 {
205         AppCanvas *app_canvas = dynamic_cast<AppCanvas *>(_Canvas);
206         BLI_assert(app_canvas != 0);
207         app_canvas->setPassDiffuse(buf, width, height);
208 }
209
210 void Controller::setPassZ(float *buf, int width, int height)
211 {
212         AppCanvas *app_canvas = dynamic_cast<AppCanvas *>(_Canvas);
213         BLI_assert(app_canvas != 0);
214         app_canvas->setPassZ(buf, width, height);
215 }
216
217 void Controller::setContext(bContext *C)
218 {
219         PythonInterpreter *py_inter = dynamic_cast<PythonInterpreter*>(_inter);
220         py_inter->setContext(C);
221 }
222
223 bool Controller::hitViewMapCache()
224 {
225         if (!_EnableViewMapCache) {
226                 return false;
227         }
228         if (sceneHashFunc.match()) {
229                 return (NULL != _ViewMap);
230         }
231         sceneHashFunc.store();
232         return false;
233 }
234
235 int Controller::LoadMesh(Render *re, ViewLayer *view_layer)
236 {
237         BlenderFileLoader loader(re, view_layer);
238
239         loader.setRenderMonitor(_pRenderMonitor);
240
241         _Chrono.start();
242
243         NodeGroup *blenderScene = loader.Load();
244
245         if (blenderScene == NULL) {
246                 if (G.debug & G_DEBUG_FREESTYLE) {
247                         cout << "Cannot load scene" << endl;
248                 }
249                 return 1;
250         }
251
252         if (blenderScene->numberOfChildren() < 1) {
253                 if (G.debug & G_DEBUG_FREESTYLE) {
254                         cout << "Empty scene" << endl;
255                 }
256                 blenderScene->destroy();
257                 delete blenderScene;
258                 return 1;
259         }
260
261         real duration = _Chrono.stop();
262         if (G.debug & G_DEBUG_FREESTYLE) {
263                 cout << "Scene loaded" << endl;
264                 printf("Mesh cleaning    : %lf\n", duration);
265                 printf("View map cache   : %s\n", _EnableViewMapCache ? "enabled" : "disabled");
266         }
267         _SceneNumFaces += loader.numFacesRead();
268
269 #if 0
270         if (loader.minEdgeSize() < _minEdgeSize) {
271                 _minEdgeSize = loader.minEdgeSize();
272         }
273 #endif
274
275 #if 0  // DEBUG
276         ScenePrettyPrinter spp;
277         blenderScene->accept(spp);
278 #endif
279
280         _RootNode->AddChild(blenderScene);
281         _RootNode->UpdateBBox(); // FIXME: Correct that by making a Renderer to compute the bbox
282
283         _pView->setModel(_RootNode);
284         //_pView->FitBBox();
285
286         if (_pRenderMonitor->testBreak())
287                 return 0;
288
289         if (_EnableViewMapCache) {
290
291                 NodeCamera *cam;
292                 if (g_freestyle.proj[3][3] != 0.0)
293                         cam = new NodeOrthographicCamera;
294                 else
295                         cam = new NodePerspectiveCamera;
296                 double proj[16];
297                 for (int i = 0; i < 4; i++) {
298                         for (int j = 0; j < 4; j++) {
299                                 proj[i * 4 + j] = g_freestyle.proj[i][j];
300                         }
301                 }
302                 cam->setProjectionMatrix(proj);
303                 _RootNode->AddChild(cam);
304                 _RootNode->AddChild(new NodeViewLayer(*re->scene, *view_layer));
305
306                 sceneHashFunc.reset();
307                 //blenderScene->accept(sceneHashFunc);
308                 _RootNode->accept(sceneHashFunc);
309                 if (G.debug & G_DEBUG_FREESTYLE) {
310                         cout << "Scene hash       : " << sceneHashFunc.toString() << endl;
311                 }
312                 if (hitViewMapCache()) {
313                         ClearRootNode();
314                         return 0;
315                 }
316                 else {
317                         delete _ViewMap;
318                         _ViewMap = NULL;
319                 }
320         }
321
322         _Chrono.start();
323
324         WXEdgeBuilder wx_builder;
325         wx_builder.setRenderMonitor(_pRenderMonitor);
326         blenderScene->accept(wx_builder);
327         _winged_edge = wx_builder.getWingedEdge();
328
329         duration = _Chrono.stop();
330         if (G.debug & G_DEBUG_FREESTYLE) {
331                 printf("WEdge building   : %lf\n", duration);
332         }
333
334 #if 0
335         _pView->setDebug(_DebugNode);
336
337         // delete stuff
338         if (0 != ws_builder) {
339                 delete ws_builder;
340                 ws_builder = 0;
341         }
342
343         soc QFileInfo qfi(iFileName);
344         soc string basename((const char*)qfi.fileName().toAscii().data());
345         char cleaned[FILE_MAX];
346         BLI_strncpy(cleaned, iFileName, FILE_MAX);
347         BLI_cleanup_file(NULL, cleaned);
348         string basename = string(cleaned);
349 #endif
350
351         _ListOfModels.push_back("Blender_models");
352
353         _Scene3dBBox = _RootNode->bbox();
354
355         _bboxDiag = (_RootNode->bbox().getMax() - _RootNode->bbox().getMin()).norm();
356         if (G.debug & G_DEBUG_FREESTYLE) {
357                 cout << "Triangles nb     : " << _SceneNumFaces << " imported, " <<
358                         _winged_edge->getNumFaces() << " retained" << endl;
359                 cout << "Bounding Box     : " << _bboxDiag << endl;
360         }
361
362         ClearRootNode();
363
364         _SceneNumFaces = _winged_edge->getNumFaces();
365         if (_SceneNumFaces == 0) {
366                 DeleteWingedEdge();
367                 return 1;
368         }
369
370         return 0;
371 }
372
373 void Controller::CloseFile()
374 {
375         WShape::setCurrentId(0);
376         _ListOfModels.clear();
377
378         // We deallocate the memory:
379         ClearRootNode();
380         DeleteWingedEdge();
381         DeleteViewMap();
382
383         // clears the canvas
384         _Canvas->Clear();
385
386         // soc: reset passes
387         setPassDiffuse(NULL, 0, 0);
388         setPassZ(NULL, 0, 0);
389 }
390
391 void Controller::ClearRootNode()
392 {
393         _pView->DetachModel();
394         if (NULL != _RootNode) {
395                 int ref = _RootNode->destroy();
396                 if (0 == ref)
397                         _RootNode->addRef();
398                 _RootNode->clearBBox();
399         }
400 }
401
402 void Controller::DeleteWingedEdge()
403 {
404         if (_winged_edge) {
405                 delete _winged_edge;
406                 _winged_edge = NULL;
407         }
408
409         // clears the grid
410         _Grid.clear();
411         _Scene3dBBox.clear();
412         _SceneNumFaces = 0;
413 #if 0
414         _minEdgeSize = DBL_MAX;
415 #endif
416 }
417
418 void Controller::DeleteViewMap(bool freeCache)
419 {
420 #if 0
421         _pView->DetachSilhouette();
422         if (NULL != _SilhouetteNode) {
423                 int ref = _SilhouetteNode->destroy();
424                 if (0 == ref) {
425                         delete _SilhouetteNode;
426                         _SilhouetteNode = NULL;
427                 }
428         }
429
430         if (NULL != _ProjectedSilhouette) {
431                 int ref = _ProjectedSilhouette->destroy();
432                 if (0 == ref) {
433                         delete _ProjectedSilhouette;
434                         _ProjectedSilhouette = NULL;
435                 }
436         }
437         if (NULL != _VisibleProjectedSilhouette) {
438                 int ref = _VisibleProjectedSilhouette->destroy();
439                 if (0 == ref) {
440                         delete _VisibleProjectedSilhouette;
441                         _VisibleProjectedSilhouette = NULL;
442                 }
443         }
444
445         _pView->DetachDebug();
446         if (NULL != _DebugNode) {
447                 int ref = _DebugNode->destroy();
448                 if (0 == ref)
449                         _DebugNode->addRef();
450         }
451 #endif
452
453         if (NULL != _ViewMap) {
454                 if (freeCache || !_EnableViewMapCache) {
455                         delete _ViewMap;
456                         _ViewMap = NULL;
457                         prevSceneHash = -1.0;
458                 }
459                 else {
460                         _ViewMap->Clean();
461                 }
462         }
463 }
464
465 void Controller::ComputeViewMap()
466 {
467         if (!_ListOfModels.size())
468                 return;
469
470         DeleteViewMap(true);
471
472         // retrieve the 3D viewpoint and transformations information
473         //----------------------------------------------------------
474         // Save the viewpoint context at the view level in order 
475         // to be able to restore it later:
476
477         // Restore the context of view:
478         // we need to perform all these operations while the 
479         // 3D context is on.
480         Vec3f vp(UNPACK3(g_freestyle.viewpoint));
481
482 #if 0
483         if (G.debug & G_DEBUG_FREESTYLE) {
484                 cout << "mv" << endl;
485         }
486 #endif
487         real mv[4][4];
488         for (int i = 0; i < 4; i++) {
489                 for (int j = 0; j < 4; j++) {
490                         mv[i][j] = g_freestyle.mv[i][j];
491 #if 0
492                         if (G.debug & G_DEBUG_FREESTYLE) {
493                                 cout << mv[i][j] << " ";
494                         }
495 #endif
496                 }
497 #if 0
498                 if (G.debug & G_DEBUG_FREESTYLE) {
499                         cout << endl;
500                 }
501 #endif
502         }
503
504 #if 0
505         if (G.debug & G_DEBUG_FREESTYLE) {
506                 cout << "\nproj" << endl;
507         }
508 #endif
509         real proj[4][4];
510         for (int i = 0; i < 4; i++) {
511                 for (int j = 0; j < 4; j++) {
512                         proj[i][j] = g_freestyle.proj[i][j];
513 #if 0
514                         if (G.debug & G_DEBUG_FREESTYLE) {
515                                 cout << proj[i][j] << " ";
516                         }
517 #endif
518                 }
519 #if 0
520                 if (G.debug & G_DEBUG_FREESTYLE) {
521                         cout << endl;
522                 }
523 #endif
524         }
525
526         int viewport[4];
527         for (int i = 0; i < 4; i++)
528                 viewport[i] = g_freestyle.viewport[i];
529
530 #if 0
531         if (G.debug & G_DEBUG_FREESTYLE) {
532                 cout << "\nfocal:" << _pView->GetFocalLength() << endl << endl;
533         }
534 #endif
535
536         // Flag the WXEdge structure for silhouette edge detection:
537         //----------------------------------------------------------
538
539         if (G.debug & G_DEBUG_FREESTYLE) {
540                 cout << "\n===  Detecting silhouette edges  ===" << endl;
541         }
542         _Chrono.start();
543
544         edgeDetector.setViewpoint(vp);
545         edgeDetector.enableOrthographicProjection(proj[3][3] != 0.0);
546         edgeDetector.enableRidgesAndValleysFlag(_ComputeRidges);
547         edgeDetector.enableSuggestiveContours(_ComputeSuggestive);
548         edgeDetector.enableMaterialBoundaries(_ComputeMaterialBoundaries);
549         edgeDetector.enableFaceSmoothness(_EnableFaceSmoothness);
550         edgeDetector.setCreaseAngle(_creaseAngle);
551         edgeDetector.setSphereRadius(_sphereRadius);
552         edgeDetector.setSuggestiveContourKrDerivativeEpsilon(_suggestiveContourKrDerivativeEpsilon);
553         edgeDetector.setRenderMonitor(_pRenderMonitor);
554         edgeDetector.processShapes(*_winged_edge);
555
556         real duration = _Chrono.stop();
557         if (G.debug & G_DEBUG_FREESTYLE) {
558                 printf("Feature lines    : %lf\n", duration);
559         }
560
561         if (_pRenderMonitor->testBreak())
562                 return;
563
564         // Builds the view map structure from the flagged WSEdge structure:
565         //----------------------------------------------------------
566         ViewMapBuilder vmBuilder;
567         vmBuilder.setEnableQI(_EnableQI);
568         vmBuilder.setViewpoint(vp);
569         vmBuilder.setTransform(mv, proj, viewport, _pView->GetFocalLength(), _pView->GetAspect(), _pView->GetFovyRadian());
570         vmBuilder.setFrustum(_pView->znear(), _pView->zfar());
571         vmBuilder.setGrid(&_Grid);
572         vmBuilder.setRenderMonitor(_pRenderMonitor);
573
574 #if 0
575         // Builds a tesselated form of the silhouette for display purpose:
576         //---------------------------------------------------------------
577         ViewMapTesselator3D sTesselator3d;
578         ViewMapTesselator2D sTesselator2d;
579         sTesselator2d.setNature(_edgeTesselationNature);
580         sTesselator3d.setNature(_edgeTesselationNature);
581 #endif
582
583         if (G.debug & G_DEBUG_FREESTYLE) {
584                 cout << "\n===  Building the view map  ===" << endl;
585         }
586         _Chrono.start();
587         // Build View Map
588         _ViewMap = vmBuilder.BuildViewMap(*_winged_edge, _VisibilityAlgo, _EPSILON, _Scene3dBBox, _SceneNumFaces);
589         _ViewMap->setScene3dBBox(_Scene3dBBox);
590
591         if (G.debug & G_DEBUG_FREESTYLE) {
592                 printf("ViewMap edge count : %i\n", _ViewMap->viewedges_size());
593         }
594
595 #if 0
596         // Tesselate the 3D edges:
597         _SilhouetteNode = sTesselator3d.Tesselate(_ViewMap);
598         _SilhouetteNode->addRef();
599
600         // Tesselate 2D edges
601         _ProjectedSilhouette = sTesselator2d.Tesselate(_ViewMap);
602         _ProjectedSilhouette->addRef();
603 #endif
604
605         duration = _Chrono.stop();
606         if (G.debug & G_DEBUG_FREESTYLE) {
607                 printf("ViewMap building : %lf\n", duration);
608         }
609
610 #if 0
611         _pView->AddSilhouette(_SilhouetteNode);
612         _pView->AddSilhouette(_WRoot);
613         _pView->Add2DSilhouette(_ProjectedSilhouette);
614         _pView->Add2DVisibleSilhouette(_VisibleProjectedSilhouette);
615         _pView->AddDebug(_DebugNode);
616 #endif
617
618         // Draw the steerable density map:
619         //--------------------------------
620         if (_ComputeSteerableViewMap) {
621                 ComputeSteerableViewMap();
622         }
623         // Reset Style modules modification flags
624         resetModified(true);
625
626         DeleteWingedEdge();
627 }
628
629 void Controller::ComputeSteerableViewMap()
630 {
631 #if 0  //soc
632         if ((!_Canvas) || (!_ViewMap))
633                 return;
634
635         // Build 4 nodes containing the edges in the 4 directions
636         NodeGroup *ng[Canvas::NB_STEERABLE_VIEWMAP];
637         unsigned i;
638         real c = 32.0f/255.0f; // see SteerableViewMap::readSteerableViewMapPixel() for information about this 32.
639         for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
640                 ng[i] = new NodeGroup;
641         }
642         NodeShape *completeNS = new NodeShape;
643         completeNS->material().setDiffuse(c,c,c,1);
644         ng[Canvas::NB_STEERABLE_VIEWMAP-1]->AddChild(completeNS);
645         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
646         svm->Reset();
647
648         ViewMap::fedges_container& fedges = _ViewMap->FEdges();
649         LineRep * fRep;
650         NodeShape *ns;
651         for (ViewMap::fedges_container::iterator f = fedges.begin(), fend = fedges.end();
652              f != fend;
653              ++f)
654         {
655                 if ((*f)->viewedge()->qi() != 0)
656                         continue;
657                 fRep = new LineRep((*f)->vertexA()->point2d(), (*f)->vertexB()->point2d());
658                 completeNS->AddRep(fRep); // add to the complete map anyway
659                 double *oweights = svm->AddFEdge(*f);
660                 for (i = 0; i < (Canvas::NB_STEERABLE_VIEWMAP - 1); ++i) {
661                         ns = new NodeShape;
662                         double wc = oweights[i]*c;
663                         if (oweights[i] == 0)
664                                 continue;
665                         ns->material().setDiffuse(wc, wc, wc, 1);
666                         ns->AddRep(fRep);
667                         ng[i]->AddChild(ns);
668                 }
669         }
670
671         GrayImage *img[Canvas::NB_STEERABLE_VIEWMAP];
672         //#ifdef WIN32
673         QGLBasicWidget offscreenBuffer(_pView, "SteerableViewMap", _pView->width(), _pView->height());
674         QPixmap pm;
675         QImage qimg;
676         for (i = 0; i < Canvas::NB_STEERABLE_VIEWMAP; ++i) {
677                 offscreenBuffer.AddNode(ng[i]);
678 #if 0
679                 img[i] = new GrayImage(_pView->width(), _pView->height());
680                 offscreenBuffer.readPixels(0,0,_pView->width(), _pView->height(), img[i]->getArray());
681 #endif
682                 pm = offscreenBuffer.renderPixmap(_pView->width(), _pView->height());
683
684                 if (pm.isNull()) {
685                         if (G.debug & G_DEBUG_FREESTYLE) {
686                                 cout << "BuildViewMap Warning: couldn't render the steerable ViewMap" << endl;
687                         }
688                 }
689                 //pm.save(QString("steerable") + QString::number(i) + QString(".bmp"), "BMP");
690                 // FIXME!! Lost of time !
691                 qimg = pm.toImage();
692                 // FIXME !! again!
693                 img[i] = new GrayImage(_pView->width(), _pView->height());
694                 for (unsigned int y = 0; y < img[i]->height(); ++y) {
695                         for (unsigned int x = 0; x < img[i]->width(); ++x) {
696                                 //img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)) / 255.0f);
697                                 img[i]->setPixel(x, y, (float)qGray(qimg.pixel(x, y)));
698                                 //float c = qGray(qimg.pixel(x, y));
699                                 //img[i]->setPixel(x, y, qGray(qimg.pixel(x, y)));
700                         }
701                 }
702                 offscreenBuffer.DetachNode(ng[i]);
703                 ng[i]->destroy();
704                 delete ng[i];
705                 // check
706 #if 0
707                 qimg = QImage(_pView->width(), _pView->height(), 32);
708                 for (unsigned int y = 0; y < img[i]->height(); ++y) {
709                         for (unsigned int x = 0; x < img[i]->width(); ++x) {
710                                 float v = img[i]->pixel(x, y);
711                                 qimg.setPixel(x, y, qRgb(v, v, v));
712                         }
713                 }
714                 qimg.save(QString("newsteerable") + QString::number(i) + QString(".bmp"), "BMP");
715 #endif
716         }
717
718
719         svm->buildImagesPyramids(img, false, 0, 1.0f);
720 #endif
721 }
722
723 void Controller::saveSteerableViewMapImages()
724 {
725         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
726         if (!svm) {
727                 cerr << "the Steerable ViewMap has not been computed yet" << endl;
728                 return;
729         }
730         svm->saveSteerableViewMap();
731 }
732
733 void Controller::toggleVisibilityAlgo()
734 {
735         if (_VisibilityAlgo == ViewMapBuilder::ray_casting) {
736                 _VisibilityAlgo = ViewMapBuilder::ray_casting_fast;
737         }
738         else if (_VisibilityAlgo == ViewMapBuilder::ray_casting_fast) {
739                 _VisibilityAlgo = ViewMapBuilder::ray_casting_very_fast;
740         }
741         else {
742                 _VisibilityAlgo = ViewMapBuilder::ray_casting;
743         }
744 }
745
746 void Controller::setVisibilityAlgo(int algo)
747 {
748         switch (algo) {
749                 case FREESTYLE_ALGO_REGULAR:
750                         _VisibilityAlgo = ViewMapBuilder::ray_casting;
751                         break;
752                 case FREESTYLE_ALGO_FAST:
753                         _VisibilityAlgo = ViewMapBuilder::ray_casting_fast;
754                         break;
755                 case FREESTYLE_ALGO_VERYFAST:
756                         _VisibilityAlgo = ViewMapBuilder::ray_casting_very_fast;
757                         break;
758                 case FREESTYLE_ALGO_CULLED_ADAPTIVE_TRADITIONAL:
759                         _VisibilityAlgo = ViewMapBuilder::ray_casting_culled_adaptive_traditional;
760                         break;
761                 case FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL:
762                         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_traditional;
763                         break;
764                 case FREESTYLE_ALGO_CULLED_ADAPTIVE_CUMULATIVE:
765                         _VisibilityAlgo = ViewMapBuilder::ray_casting_culled_adaptive_cumulative;
766                         break;
767                 case FREESTYLE_ALGO_ADAPTIVE_CUMULATIVE:
768                         _VisibilityAlgo = ViewMapBuilder::ray_casting_adaptive_cumulative;
769                         break;
770         }
771 }
772
773 int Controller::getVisibilityAlgo()
774 {
775         switch (_VisibilityAlgo) {
776                 case ViewMapBuilder::ray_casting:
777                         return FREESTYLE_ALGO_REGULAR;
778                 case ViewMapBuilder::ray_casting_fast:
779                         return FREESTYLE_ALGO_FAST;
780                 case ViewMapBuilder::ray_casting_very_fast:
781                         return FREESTYLE_ALGO_VERYFAST;
782                 case ViewMapBuilder::ray_casting_culled_adaptive_traditional:
783                         return FREESTYLE_ALGO_CULLED_ADAPTIVE_TRADITIONAL;
784                 case ViewMapBuilder::ray_casting_adaptive_traditional:
785                         return FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL;
786                 case ViewMapBuilder::ray_casting_culled_adaptive_cumulative:
787                         return FREESTYLE_ALGO_CULLED_ADAPTIVE_CUMULATIVE;
788                 case ViewMapBuilder::ray_casting_adaptive_cumulative:
789                         return FREESTYLE_ALGO_ADAPTIVE_CUMULATIVE;
790         }
791
792         // ray_casting_adaptive_traditional is the most exact replacement
793         // for legacy code
794         return FREESTYLE_ALGO_ADAPTIVE_TRADITIONAL;
795 }
796
797 void Controller::setViewMapCache(bool iBool)
798 {
799         _EnableViewMapCache = iBool;
800 }
801
802 bool Controller::getViewMapCache() const
803 {
804         return _EnableViewMapCache;
805 }
806
807 void Controller::setQuantitativeInvisibility(bool iBool)
808 {
809         _EnableQI = iBool;
810 }
811
812 bool Controller::getQuantitativeInvisibility() const
813 {
814         return _EnableQI;
815 }
816
817 void Controller::setFaceSmoothness(bool iBool)
818 {
819         _EnableFaceSmoothness = iBool;
820 }
821
822 bool Controller::getFaceSmoothness() const
823 {
824         return _EnableFaceSmoothness;
825 }
826
827 void Controller::setComputeRidgesAndValleysFlag(bool iBool)
828 {
829         _ComputeRidges = iBool;
830 }
831
832 bool Controller::getComputeRidgesAndValleysFlag() const
833 {
834         return _ComputeRidges;
835 }
836
837 void Controller::setComputeSuggestiveContoursFlag(bool b)
838 {
839         _ComputeSuggestive = b;
840 }
841
842 bool Controller::getComputeSuggestiveContoursFlag() const
843 {
844         return _ComputeSuggestive;
845 }
846
847 void Controller::setComputeMaterialBoundariesFlag(bool b)
848 {
849         _ComputeMaterialBoundaries = b;
850 }
851
852 bool Controller::getComputeMaterialBoundariesFlag() const
853 {
854         return _ComputeMaterialBoundaries;
855 }
856
857 void Controller::setComputeSteerableViewMapFlag(bool iBool)
858 {
859         _ComputeSteerableViewMap = iBool;
860 }
861
862 bool Controller::getComputeSteerableViewMapFlag() const
863 {
864         return _ComputeSteerableViewMap;
865 }
866
867 int Controller::DrawStrokes()
868 {
869         if (_ViewMap == 0)
870                 return 0;
871
872         if (G.debug & G_DEBUG_FREESTYLE) {
873                 cout << "\n===  Stroke drawing  ===" << endl;
874         }
875         _Chrono.start();
876         _Canvas->Draw();
877         real d = _Chrono.stop();
878         int strokeCount = _Canvas->getStrokeCount();
879         if (G.debug & G_DEBUG_FREESTYLE) {
880                 cout << "Strokes generation  : " << d << endl;
881                 cout << "Stroke count  : " << strokeCount << endl;
882         }
883         resetModified();
884         DeleteViewMap();
885         return strokeCount;
886 }
887
888 void Controller::ResetRenderCount()
889 {
890         _render_count = 0;
891 }
892
893 Render *Controller::RenderStrokes(Render *re, bool render)
894 {
895         int totmesh = 0;
896         _Chrono.start();
897         BlenderStrokeRenderer *blenderRenderer = new BlenderStrokeRenderer(re, ++_render_count);
898         if (render) {
899                 _Canvas->Render(blenderRenderer);
900                 totmesh = blenderRenderer->GenerateScene();
901         }
902         real d = _Chrono.stop();
903         if (G.debug & G_DEBUG_FREESTYLE) {
904                 cout << "Temporary scene generation: " << d << endl;
905         }
906         _Chrono.start();
907         Render *freestyle_render = blenderRenderer->RenderScene(re, render);
908         d = _Chrono.stop();
909         if (G.debug & G_DEBUG_FREESTYLE) {
910                 cout << "Stroke rendering  : " << d << endl;
911
912                 uintptr_t mem_in_use = MEM_get_memory_in_use();
913                 uintptr_t mmap_in_use = MEM_get_mapped_memory_in_use();
914                 uintptr_t peak_memory = MEM_get_peak_memory();
915
916                 float megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
917                 float mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
918                 float megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
919
920                 printf("%d objs, %d verts, %d faces, mem %.2fM (%.2fM, peak %.2fM)\n",
921                        totmesh, freestyle_render->i.totvert, freestyle_render->i.totface,
922                        megs_used_memory, mmap_used_memory, megs_peak_memory);
923         }
924         delete blenderRenderer;
925
926         return freestyle_render;
927 }
928
929 void Controller::InsertStyleModule(unsigned index, const char *iFileName)
930 {
931         if (!BLI_path_extension_check(iFileName, ".py")) {
932                 cerr << "Error: Cannot load \"" << string(iFileName) << "\", unknown extension" << endl;
933                 return;
934         }
935
936         StyleModule *sm = new StyleModule(iFileName, _inter);
937         _Canvas->InsertStyleModule(index, sm);
938 }
939
940 void Controller::InsertStyleModule(unsigned index, const char *iName, const char *iBuffer)
941 {
942         StyleModule *sm = new BufferedStyleModule(iBuffer, iName, _inter);
943         _Canvas->InsertStyleModule(index, sm);
944 }
945
946 void Controller::InsertStyleModule(unsigned index, const char *iName, struct Text *iText)
947 {
948         StyleModule *sm = new BlenderStyleModule(iText, iName, _inter);
949         _Canvas->InsertStyleModule(index, sm);
950 }
951
952 void Controller::AddStyleModule(const char * /*iFileName*/)
953 {
954         //_pStyleWindow->Add(iFileName);
955 }
956
957 void Controller::RemoveStyleModule(unsigned index)
958 {
959         _Canvas->RemoveStyleModule(index);
960 }
961
962 void Controller::Clear()
963 {
964         _Canvas->Clear();
965 }
966
967 void Controller::ReloadStyleModule(unsigned index, const char * iFileName)
968 {
969         StyleModule *sm = new StyleModule(iFileName, _inter);
970         _Canvas->ReplaceStyleModule(index, sm);
971 }
972
973 void Controller::SwapStyleModules(unsigned i1, unsigned i2)
974 {
975         _Canvas->SwapStyleModules(i1, i2);
976 }
977
978 void Controller::toggleLayer(unsigned index, bool iDisplay)
979 {
980         _Canvas->setVisible(index, iDisplay);
981 }
982
983 void Controller::setModified(unsigned index, bool iMod)
984 {
985         //_pStyleWindow->setModified(index, iMod);
986         _Canvas->setModified(index, iMod);
987         updateCausalStyleModules(index + 1);
988 }
989
990 void Controller::updateCausalStyleModules(unsigned index)
991 {
992         vector<unsigned> vec;
993         _Canvas->causalStyleModules(vec, index);
994         for (vector<unsigned>::const_iterator it = vec.begin(); it != vec.end(); it++) {
995                 //_pStyleWindow->setModified(*it, true);
996                 _Canvas->setModified(*it, true);
997         }
998 }
999
1000 void Controller::resetModified(bool iMod)
1001 {
1002         //_pStyleWindow->resetModified(iMod);
1003         _Canvas->resetModified(iMod);
1004 }
1005
1006 NodeGroup * Controller::BuildRep(vector<ViewEdge*>::iterator vedges_begin, vector<ViewEdge*>::iterator vedges_end)
1007 {
1008         ViewMapTesselator2D tesselator2D;
1009         FrsMaterial mat;
1010         mat.setDiffuse(1, 1, 0.3, 1);
1011         tesselator2D.setFrsMaterial(mat);
1012
1013         return (tesselator2D.Tesselate(vedges_begin, vedges_end));
1014 }
1015
1016 void Controller::toggleEdgeTesselationNature(Nature::EdgeNature iNature)
1017 {
1018         _edgeTesselationNature ^= (iNature);
1019         ComputeViewMap();
1020 }
1021
1022 void Controller::setModelsDir(const string& /*dir*/)
1023 {
1024         //_current_dirs->setValue("models/dir", dir);
1025 }
1026
1027 string Controller::getModelsDir() const
1028 {
1029         string dir = ".";
1030         //_current_dirs->getValue("models/dir", dir);
1031         return dir;
1032 }
1033
1034 void Controller::setModulesDir(const string& /*dir*/)
1035 {
1036         //_current_dirs->setValue("modules/dir", dir);
1037 }
1038
1039 string Controller::getModulesDir() const
1040 {
1041         string dir = ".";
1042         //_current_dirs->getValue("modules/dir", dir);
1043         return dir;
1044 }
1045
1046 void Controller::resetInterpreter()
1047 {
1048         if (_inter)
1049                 _inter->reset();
1050 }
1051
1052
1053 void Controller::displayDensityCurves(int x, int y)
1054 {
1055         SteerableViewMap * svm = _Canvas->getSteerableViewMap();
1056         if (!svm)
1057                 return;
1058
1059         unsigned int i, j;
1060         typedef vector<Vec3r> densityCurve;
1061         vector<densityCurve> curves(svm->getNumberOfOrientations() + 1);
1062         vector<densityCurve> curvesDirection(svm->getNumberOfPyramidLevels());
1063
1064         // collect the curves values
1065         unsigned nbCurves = svm->getNumberOfOrientations() + 1;
1066         unsigned nbPoints = svm->getNumberOfPyramidLevels();
1067         if (!nbPoints)
1068                 return;
1069
1070         // build the density/nbLevels curves for each orientation
1071         for (i = 0; i < nbCurves; ++i) {
1072                 for (j = 0; j < nbPoints; ++j) {
1073                         curves[i].push_back(Vec3r(j, svm->readSteerableViewMapPixel(i, j, x, y), 0));
1074                 }
1075         }
1076         // build the density/nbOrientations curves for each level
1077         for (i = 0; i < nbPoints; ++i) {
1078                 for (j = 0; j < nbCurves; ++j) {
1079                         curvesDirection[i].push_back(Vec3r(j, svm->readSteerableViewMapPixel(j, i, x, y), 0));
1080                 }
1081         }
1082
1083         // display the curves
1084 #if 0
1085         for (i = 0; i < nbCurves; ++i)
1086                 _pDensityCurvesWindow->setOrientationCurve(i, Vec2d(0, 0), Vec2d(nbPoints, 1), curves[i], "scale", "density");
1087         for (i = 1; i <= 8; ++i)
1088                 _pDensityCurvesWindow->setLevelCurve(i, Vec2d(0, 0), Vec2d(nbCurves, 1), curvesDirection[i],
1089                                                      "orientation", "density");
1090         _pDensityCurvesWindow->show();
1091 #endif
1092 }
1093
1094 void Controller::init_options()
1095 {
1096         // from AppOptionsWindow.cpp
1097         // Default init options
1098
1099         Config::Path * cpath = Config::Path::getInstance();
1100
1101         // Directories
1102         ViewMapIO::Options::setModelsPath(cpath->getModelsPath());
1103         TextureManager::Options::setPatternsPath(cpath->getPatternsPath());
1104         TextureManager::Options::setBrushesPath(cpath->getModelsPath());
1105
1106         // ViewMap Format
1107         ViewMapIO::Options::rmFlags(ViewMapIO::Options::FLOAT_VECTORS);
1108         ViewMapIO::Options::rmFlags(ViewMapIO::Options::NO_OCCLUDERS);
1109         setComputeSteerableViewMapFlag(false);
1110
1111         // Visibility
1112         setQuantitativeInvisibility(true);
1113
1114         // soc: initialize canvas
1115         _Canvas->init();
1116
1117         // soc: initialize passes
1118         setPassDiffuse(NULL, 0, 0);
1119         setPassZ(NULL, 0, 0);
1120 }
1121
1122 } /* namespace Freestyle */