A few attempts to reduce the amount of memory consumption in Freestyle.
[blender-staging.git] / source / blender / freestyle / intern / blender_interface / FRS_freestyle.cpp
1 #include "../application/Controller.h"
2 #include "../application/AppView.h"
3 #include "../application/AppConfig.h"
4 #include "../application/AppCanvas.h"
5
6 #include <iostream>
7 #include <map>
8 #include <set>
9 using namespace std;
10
11 #ifdef __cplusplus
12 extern "C" {
13 #endif
14
15 #include "MEM_guardedalloc.h"
16
17 #include "DNA_camera_types.h"
18 #include "DNA_text_types.h"
19 #include "DNA_freestyle_types.h"
20
21 #include "BKE_global.h"
22 #include "BKE_library.h"
23 #include "BKE_linestyle.h"
24 #include "BKE_main.h"
25 #include "BKE_text.h"
26 #include "BLI_blenlib.h"
27 #include "BLI_math.h"
28 #include "BPY_extern.h"
29
30 #include "renderpipeline.h"
31 #include "pixelblending.h"
32
33 #include "../../FRS_freestyle.h"
34 #include "../../FRS_freestyle_config.h"
35
36         // Freestyle configuration
37         static short freestyle_is_initialized = 0;
38         static Config::Path *pathconfig = NULL;
39         static Controller *controller = NULL;
40         static AppView *view = NULL;
41
42         // camera information
43         float freestyle_viewpoint[3];
44         float freestyle_mv[4][4];
45         float freestyle_proj[4][4];
46         int freestyle_viewport[4];
47         
48         // current scene
49         Scene *freestyle_scene;
50
51         string default_module_path;
52
53         //=======================================================
54         //   Initialization 
55         //=======================================================
56
57         void FRS_initialize() {
58                 
59                 if( freestyle_is_initialized )
60                         return;
61
62                 pathconfig = new Config::Path;
63                 controller = new Controller();
64                 view = new AppView;
65                 controller->setView(view);
66                 controller->Clear();
67                 freestyle_scene = NULL;
68                         
69                 default_module_path = pathconfig->getProjectDir() + Config::DIR_SEP + "style_modules" + Config::DIR_SEP + "contour.py";
70                         
71                 freestyle_is_initialized = 1;
72         }
73         
74         void FRS_set_context(bContext* C) {
75                 cout << "FRS_set_context: context 0x" << C << " scene 0x" << CTX_data_scene(C) << endl;
76                 controller->setContext(C);
77         }
78
79         void FRS_exit() {
80                 delete pathconfig;
81                 delete controller;
82                 delete view;
83         }
84
85         //=======================================================
86         //   Rendering 
87         //=======================================================
88
89         static void init_view(Render* re){
90                 float ycor = ((float)re->r.yasp) / ((float)re->r.xasp);
91                 int width = re->r.xsch;
92                 int height = (int)(((float)re->r.ysch) * ycor);
93                 int xmin = re->r.border.xmin * width;
94                 int xmax = re->r.border.xmax * width;
95                 int ymin = re->r.border.ymin * height;
96                 int ymax = re->r.border.ymax * height;
97                 
98                 freestyle_viewport[0] = freestyle_viewport[1] = 0;
99                 freestyle_viewport[2] = width;
100                 freestyle_viewport[3] = height;
101                 
102                 view->setWidth( width );
103                 view->setHeight( height );
104                 view->setBorder( xmin, ymin, xmax, ymax );
105
106                 cout << "\n===  Dimensions of the 2D image coordinate system  ===" << endl;
107                 cout << "Width  : " << width << endl;
108                 cout << "Height : " << height << endl;
109                 if (re->r.mode & R_BORDER)
110                         cout << "Border : (" << xmin << ", " << ymin << ") - (" << xmax << ", " << ymax << ")" << endl;
111         }
112
113         static void init_camera(Render* re){
114                 // It is assumed that imported meshes are in the camera coordinate system.
115                 // Therefore, the view point (i.e., camera position) is at the origin, and
116                 // the the model-view matrix is simply the identity matrix.
117
118                 freestyle_viewpoint[0] = 0.0;
119                 freestyle_viewpoint[1] = 0.0;
120                 freestyle_viewpoint[2] = 0.0;
121                 
122                 for( int i = 0; i < 4; i++ )
123                    for( int j = 0; j < 4; j++ )
124                         freestyle_mv[i][j] = (i == j) ? 1.0 : 0.0;
125                 
126                 for( int i = 0; i < 4; i++ )
127                    for( int j = 0; j < 4; j++ )
128                         freestyle_proj[i][j] = re->winmat[i][j];
129
130                 //print_m4("mv", freestyle_mv);
131                 //print_m4("proj", freestyle_proj);
132         }
133
134         static Text *create_lineset_handler(char *layer_name, char *lineset_name)
135         {
136                 Text *text = add_empty_text(lineset_name);
137                 write_text(text, "import parameter_editor; parameter_editor.process('");
138                 write_text(text, layer_name);
139                 write_text(text, "', '");
140                 write_text(text, lineset_name);
141                 write_text(text, "')\n");
142                 return text;
143         }
144
145         static void prepare(Render* re, SceneRenderLayer* srl ) {
146                                 
147                 // load mesh
148         re->i.infostr= "Freestyle: Mesh loading";
149                 re->stats_draw(re->sdh, &re->i);
150         re->i.infostr= NULL;
151                 if( controller->LoadMesh(re, srl) ) // returns if scene cannot be loaded or if empty
152                         return;
153         if( re->test_break(re->tbh) )
154             return;
155                 
156                 // add style modules
157                 FreestyleConfig* config = &srl->freestyleConfig;
158                 
159                 cout << "\n===  Rendering options  ===" << endl;
160                 int layer_count = 0;
161                 
162                 switch (config->mode) {
163                 case FREESTYLE_CONTROL_SCRIPT_MODE:
164                         cout << "Modules :"<< endl;
165                         for (FreestyleModuleConfig* module_conf = (FreestyleModuleConfig *)config->modules.first; module_conf; module_conf = module_conf->next) {
166                                 if( module_conf->is_displayed ) {
167                                         cout << "  " << layer_count+1 << ": " << module_conf->module_path << endl;
168                                         controller->InsertStyleModule( layer_count, module_conf->module_path );
169                                         controller->toggleLayer(layer_count, true);
170                                         layer_count++;
171                                 }
172                         }
173                         cout << endl;
174                         controller->setComputeRidgesAndValleysFlag( (config->flags & FREESTYLE_RIDGES_AND_VALLEYS_FLAG) ? true : false);
175                         controller->setComputeSuggestiveContoursFlag( (config->flags & FREESTYLE_SUGGESTIVE_CONTOURS_FLAG) ? true : false);
176                         controller->setComputeMaterialBoundariesFlag( (config->flags & FREESTYLE_MATERIAL_BOUNDARIES_FLAG) ? true : false);
177                         break;
178                 case FREESTYLE_CONTROL_EDITOR_MODE:
179                         int use_ridges_and_valleys = 0;
180                         int use_suggestive_contours = 0;
181                         int use_material_boundaries = 0;
182                         cout << "Linesets:"<< endl;
183                         for (FreestyleLineSet *lineset = (FreestyleLineSet *)config->linesets.first; lineset; lineset = lineset->next) {
184                                 if (lineset->flags & FREESTYLE_LINESET_ENABLED) {
185                                         cout << "  " << layer_count+1 << ": " << lineset->name << " - " << lineset->linestyle->id.name+2 << endl;
186                                         Text *text = create_lineset_handler(srl->name, lineset->name);
187                                         controller->InsertStyleModule( layer_count, lineset->name, text );
188                                         controller->toggleLayer(layer_count, true);
189                                         if (!(lineset->selection & FREESTYLE_SEL_EDGE_TYPES) || !lineset->edge_types) {
190                                                 ++use_ridges_and_valleys;
191                                                 ++use_suggestive_contours;
192                                                 ++use_material_boundaries;
193                                         } else if (lineset->flags & FREESTYLE_LINESET_FE_NOT) {
194                                                 if (!(lineset->edge_types & ~FREESTYLE_FE_RIDGE) ||
195                                                         !(lineset->edge_types & ~FREESTYLE_FE_VALLEY) ||
196                                                         (lineset->flags & FREESTYLE_LINESET_FE_AND))
197                                                                 ++use_ridges_and_valleys;
198                                                 if (lineset->edge_types & ~FREESTYLE_FE_SUGGESTIVE_CONTOUR)
199                                                         ++use_suggestive_contours;
200                                                 if (lineset->edge_types & ~FREESTYLE_FE_MATERIAL_BOUNDARY)
201                                                         ++use_material_boundaries;
202                                         } else {
203                                                 if (lineset->edge_types & (FREESTYLE_FE_RIDGE | FREESTYLE_FE_VALLEY))
204                                                         ++use_ridges_and_valleys;
205                                                 if (lineset->edge_types & FREESTYLE_FE_SUGGESTIVE_CONTOUR)
206                                                         ++use_suggestive_contours;
207                                                 if (lineset->edge_types & FREESTYLE_FE_MATERIAL_BOUNDARY)
208                                                         ++use_material_boundaries;
209                                         }
210                                         layer_count++;
211                                 }
212                         }
213                         controller->setComputeRidgesAndValleysFlag( use_ridges_and_valleys > 0 );
214                         controller->setComputeSuggestiveContoursFlag( use_suggestive_contours > 0 );
215                         controller->setComputeMaterialBoundariesFlag( use_material_boundaries > 0 );
216                         break;
217                 }
218                 
219                 // set parameters
220                 controller->setCreaseAngle( config->crease_angle );
221                 controller->setSphereRadius( config->sphere_radius );
222                 controller->setSuggestiveContourKrDerivativeEpsilon( config->dkr_epsilon ) ;
223
224                 cout << "Crease angle : " << controller->getCreaseAngle() << endl;
225                 cout << "Sphere radius : " << controller->getSphereRadius() << endl;
226                 cout << "Redges and valleys : " << (controller->getComputeRidgesAndValleysFlag() ? "enabled" : "disabled") << endl;
227                 cout << "Suggestive contours : " << (controller->getComputeSuggestiveContoursFlag() ? "enabled" : "disabled") << endl;
228                 cout << "Suggestive contour Kr derivative epsilon : " << controller->getSuggestiveContourKrDerivativeEpsilon() << endl;
229                 cout << "Material boundaries : " << (controller->getComputeMaterialBoundariesFlag() ? "enabled" : "disabled") << endl;
230                 cout << endl;
231
232         // set diffuse and z depth passes
233         RenderLayer *rl = RE_GetRenderLayer(re->result, srl->name);
234                 bool diffuse = false, z = false;
235                 for (RenderPass *rpass = (RenderPass *)rl->passes.first; rpass; rpass = rpass->next) {
236                         switch (rpass->passtype) {
237                         case SCE_PASS_DIFFUSE:
238                                 controller->setPassDiffuse(rpass->rect, rpass->rectx, rpass->recty);
239                                 diffuse = true;
240                                 break;
241                         case SCE_PASS_Z:
242                                 controller->setPassZ(rpass->rect, rpass->rectx, rpass->recty);
243                                 z = true;
244                                 break;
245                         }
246                 }
247         cout << "Passes :" << endl;
248         cout << "  Diffuse = " << (diffuse ? "enabled" : "disabled") << endl;
249         cout << "  Z = " << (z ? "enabled" : "disabled") << endl;
250
251                 // compute view map
252         re->i.infostr= "Freestyle: View map creation";
253                 re->stats_draw(re->sdh, &re->i);
254         re->i.infostr= NULL;
255                 controller->ComputeViewMap();
256         }
257         
258         void FRS_composite_result(Render* re, SceneRenderLayer* srl, Render* freestyle_render)
259         {
260                 RenderLayer *rl;
261             float *src, *dest, *pixSrc, *pixDest;
262                 int x, y, rectx, recty;
263                 
264                 if( freestyle_render == NULL || freestyle_render->result == NULL )
265                         return;
266
267                 rl = render_get_active_layer( freestyle_render, freestyle_render->result );
268             if( !rl || rl->rectf == NULL) { cout << "Cannot find Freestyle result image" << endl; return; }
269                 src  = rl->rectf;
270                 //cout << "src: " << rl->rectx << " x " << rl->recty << endl;
271                 
272                 rl = RE_GetRenderLayer(re->result, srl->name);
273             if( !rl || rl->rectf == NULL) { cout << "No layer to composite to" << endl; return; }
274                 dest  = rl->rectf;
275                 //cout << "dest: " << rl->rectx << " x " << rl->recty << endl;
276
277                 rectx = re->rectx;
278                 recty = re->recty;
279             for( y = 0; y < recty; y++) {
280                 for( x = 0; x < rectx; x++) {
281                     pixSrc = src + 4 * (rectx * y + x);
282                     if( pixSrc[3] > 0.0) {
283                                         pixDest = dest + 4 * (rectx * y + x);
284                                         addAlphaOverFloat(pixDest, pixSrc);
285                                 }
286                         }
287             }
288         }
289         
290         static int displayed_layer_count( SceneRenderLayer* srl ) {
291                 int count = 0;
292
293                 switch (srl->freestyleConfig.mode) {
294                 case FREESTYLE_CONTROL_SCRIPT_MODE:
295                         for (FreestyleModuleConfig* module = (FreestyleModuleConfig *)srl->freestyleConfig.modules.first; module; module = module->next) {
296                                 if( module->is_displayed )
297                                         count++;
298                         }
299                         break;
300                 case FREESTYLE_CONTROL_EDITOR_MODE:
301                         for (FreestyleLineSet *lineset = (FreestyleLineSet *)srl->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
302                                 if (lineset->flags & FREESTYLE_LINESET_ENABLED)
303                                         count++;
304                         }
305                         break;
306                 }
307                 return count;
308         }
309
310         int FRS_is_freestyle_enabled(SceneRenderLayer* srl) {
311                 return (!(srl->layflag & SCE_LAY_DISABLE) &&
312                                 srl->layflag & SCE_LAY_FRS &&
313                                 displayed_layer_count(srl) > 0);
314         }
315         
316         void FRS_init_stroke_rendering(Render* re) {
317
318                 cout << "\n#===============================================================" << endl;
319                 cout << "#  Freestyle" << endl;
320                 cout << "#===============================================================" << endl;
321                 
322                 init_view(re);
323                 init_camera(re);
324
325                 controller->ResetRenderCount();
326         }
327         
328         Render* FRS_do_stroke_rendering(Render* re, SceneRenderLayer *srl) {
329                 
330                 Render* freestyle_render = NULL;
331                 
332                 cout << "\n----------------------------------------------------------" << endl;
333                 cout << "|  " << (re->scene->id.name+2) << "|" << srl->name << endl;
334                 cout << "----------------------------------------------------------" << endl;
335                 
336                 // prepare Freestyle:
337                 //   - load mesh
338                 //   - add style modules
339                 //   - set parameters
340                 //   - compute view map
341                 prepare(re, srl);
342
343         if( re->test_break(re->tbh) ) {
344                         controller->CloseFile();
345             return NULL;
346         }
347
348                 // render and composite Freestyle result
349                 if( controller->_ViewMap ) {
350                         
351                         // render strokes                                       
352             re->i.infostr= "Freestyle: Stroke rendering";
353             re->stats_draw(re->sdh, &re->i);
354                 re->i.infostr= NULL;
355                         freestyle_scene = re->scene;
356                         controller->DrawStrokes();
357                         freestyle_render = controller->RenderStrokes(re);
358                         controller->CloseFile();
359                         freestyle_scene = NULL;
360                         
361                         // composite result
362                         FRS_composite_result(re, srl, freestyle_render);
363                         RE_FreeRenderResult(freestyle_render->result);
364                         freestyle_render->result = NULL;
365                 }
366
367                 return freestyle_render;
368         }
369
370         void FRS_finish_stroke_rendering(Render* re) {
371                 // clear canvas
372                 controller->Clear();
373         }
374
375         //=======================================================
376         //   Freestyle Panel Configuration
377         //=======================================================
378
379         void FRS_add_freestyle_config( SceneRenderLayer* srl )
380         {               
381                 FreestyleConfig* config = &srl->freestyleConfig;
382                 
383                 config->mode = FREESTYLE_CONTROL_SCRIPT_MODE;
384
385                 config->modules.first = config->modules.last = NULL;
386                 config->flags = 0;
387                 config->sphere_radius = 1.0f;
388                 config->dkr_epsilon = 0.001f;
389                 config->crease_angle = 134.43f;
390
391                 config->linesets.first = config->linesets.last = NULL;
392         }
393         
394         void FRS_free_freestyle_config( SceneRenderLayer* srl )
395         {               
396                 FreestyleLineSet *lineset;
397
398                 for(lineset=(FreestyleLineSet *)srl->freestyleConfig.linesets.first; lineset; lineset=lineset->next) {
399                         lineset->linestyle->id.us--;
400                         lineset->linestyle = NULL;
401                 }
402                 BLI_freelistN( &srl->freestyleConfig.linesets );
403                 BLI_freelistN( &srl->freestyleConfig.modules );
404         }
405
406         void FRS_add_module(FreestyleConfig *config)
407         {
408                 FreestyleModuleConfig* module_conf = (FreestyleModuleConfig*) MEM_callocN( sizeof(FreestyleModuleConfig), "style module configuration");
409                 BLI_addtail(&config->modules, (void*) module_conf);
410                 
411                 strcpy( module_conf->module_path, default_module_path.c_str() );
412                 module_conf->is_displayed = 1;  
413         }
414         
415         void FRS_delete_module(FreestyleConfig *config, FreestyleModuleConfig *module_conf)
416         {
417                 BLI_freelinkN(&config->modules, module_conf);
418         }
419         
420         void FRS_move_module_up(FreestyleConfig *config, FreestyleModuleConfig *module_conf)
421         {
422                 BLI_remlink(&config->modules, module_conf);
423                 BLI_insertlinkbefore(&config->modules, module_conf->prev, module_conf);
424         }
425         
426         void FRS_move_module_down(FreestyleConfig *config, FreestyleModuleConfig *module_conf)
427         {                       
428                 BLI_remlink(&config->modules, module_conf);
429                 BLI_insertlinkafter(&config->modules, module_conf->next, module_conf);
430         }
431
432         void FRS_add_lineset(FreestyleConfig *config)
433         {
434                 int lineset_index = BLI_countlist(&config->linesets);
435
436                 FreestyleLineSet *lineset = (FreestyleLineSet *) MEM_callocN( sizeof(FreestyleLineSet), "Freestyle line set");
437                 BLI_addtail(&config->linesets, (void *) lineset);
438                 FRS_set_active_lineset_index(config, lineset_index);
439
440                 lineset->linestyle = FRS_new_linestyle("LineStyle", NULL);
441                 lineset->flags |= FREESTYLE_LINESET_ENABLED;
442                 lineset->selection = FREESTYLE_SEL_IMAGE_BORDER;
443                 lineset->qi = FREESTYLE_QI_VISIBLE;
444                 lineset->qi_start = 0;
445                 lineset->qi_end = 100;
446                 lineset->edge_types = FREESTYLE_FE_SILHOUETTE | FREESTYLE_FE_BORDER | FREESTYLE_FE_CREASE;
447                 lineset->group = NULL;
448                 if (lineset_index > 0)
449                         sprintf(lineset->name, "LineSet %i", lineset_index+1);
450                 else
451                         strcpy(lineset->name, "LineSet");
452                 BLI_uniquename(&config->linesets, lineset, "FreestyleLineSet", '.', BLI_STRUCT_OFFSET(FreestyleLineSet, name), sizeof(lineset->name));
453         }
454
455         void FRS_delete_active_lineset(FreestyleConfig *config)
456         {
457                 FreestyleLineSet *lineset = FRS_get_active_lineset(config);
458
459                 if (lineset) {
460                         lineset->linestyle->id.us--;
461                         lineset->linestyle = NULL;
462                         BLI_remlink(&config->linesets, lineset);
463                         MEM_freeN(lineset);
464                         FRS_set_active_lineset_index(config, 0);
465                 }
466         }
467
468         void FRS_move_active_lineset_up(FreestyleConfig *config)
469         {
470                 FreestyleLineSet *lineset = FRS_get_active_lineset(config);
471
472                 if (lineset) {
473                         BLI_remlink(&config->linesets, lineset);
474                         BLI_insertlinkbefore(&config->linesets, lineset->prev, lineset);
475                 }
476         }
477
478         void FRS_move_active_lineset_down(FreestyleConfig *config)
479         {
480                 FreestyleLineSet *lineset = FRS_get_active_lineset(config);
481
482                 if (lineset) {
483                         BLI_remlink(&config->linesets, lineset);
484                         BLI_insertlinkafter(&config->linesets, lineset->next, lineset);
485                 }
486         }
487
488         FreestyleLineSet *FRS_get_active_lineset(FreestyleConfig *config)
489         {
490                 FreestyleLineSet *lineset;
491
492                 for(lineset=(FreestyleLineSet *)config->linesets.first; lineset; lineset=lineset->next)
493                         if(lineset->flags & FREESTYLE_LINESET_CURRENT)
494                                 return lineset;
495                 return NULL;
496         }
497
498         short FRS_get_active_lineset_index(FreestyleConfig *config)
499         {
500                 FreestyleLineSet *lineset;
501                 short i;
502
503                 for(lineset=(FreestyleLineSet *)config->linesets.first, i=0; lineset; lineset=lineset->next, i++)
504                         if(lineset->flags & FREESTYLE_LINESET_CURRENT)
505                                 return i;
506                 return 0;
507         }
508
509         void FRS_set_active_lineset_index(FreestyleConfig *config, short index)
510         {
511                 FreestyleLineSet *lineset;
512                 short i;
513
514                 for(lineset=(FreestyleLineSet *)config->linesets.first, i=0; lineset; lineset=lineset->next, i++) {
515                         if(i == index)
516                                 lineset->flags |= FREESTYLE_LINESET_CURRENT;
517                         else
518                                 lineset->flags &= ~FREESTYLE_LINESET_CURRENT;
519                 }
520         }
521
522         void FRS_unlink_target_object(FreestyleConfig *config, Object *ob)
523         {
524                 FreestyleLineSet *lineset;
525
526                 for(lineset=(FreestyleLineSet *)config->linesets.first; lineset; lineset=lineset->next) {
527                         FRS_unlink_linestyle_target_object(lineset->linestyle, ob);
528                 }
529         }
530
531 #ifdef __cplusplus
532 }
533 #endif