b56522034c5368a353b9a5d126c22b791af9b4c2
[blender.git] / source / blender / blenkernel / intern / dynamicpaint.c
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  * Contributor(s): Miika Hämäläinen
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/blenkernel/intern/dynamicpaint.c
24  *  \ingroup bke
25  */
26
27 #include "MEM_guardedalloc.h"
28
29 #include <math.h>
30 #include <stdio.h>
31
32 #include "BLI_blenlib.h"
33 #include "BLI_math.h"
34 #include "BLI_kdtree.h"
35 #include "BLI_threads.h"
36 #include "BLI_utildefines.h"
37
38 #include "BLF_translation.h"
39
40 #include "DNA_anim_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_dynamicpaint_types.h"
44 #include "DNA_group_types.h" /*GroupObject*/
45 #include "DNA_material_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_modifier_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_space_types.h"
52 #include "DNA_texture_types.h"
53
54 #include "BKE_animsys.h"
55 #include "BKE_armature.h"
56 #include "BKE_bvhutils.h"   /* bvh tree */
57 #include "BKE_blender.h"
58 #include "BKE_cdderivedmesh.h"
59 #include "BKE_constraint.h"
60 #include "BKE_context.h"
61 #include "BKE_customdata.h"
62 #include "BKE_colortools.h"
63 #include "BKE_deform.h"
64 #include "BKE_depsgraph.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_dynamicpaint.h"
67 #include "BKE_effect.h"
68 #include "BKE_global.h"
69 #include "BKE_image.h"
70 #include "BKE_main.h"
71 #include "BKE_material.h"
72 #include "BKE_modifier.h"
73 #include "BKE_object.h"
74 #include "BKE_particle.h"
75 #include "BKE_pointcache.h"
76 #include "BKE_scene.h"
77 #include "BKE_texture.h"
78
79 #include "RNA_access.h"
80 #include "RNA_define.h"
81 #include "RNA_enum_types.h"
82
83 /* for image output     */
84 #include "IMB_imbuf_types.h"
85 #include "IMB_imbuf.h"
86
87 /* to read material/texture color       */
88 #include "RE_render_ext.h"
89 #include "RE_shader_ext.h"
90
91 #ifdef _OPENMP
92 #  include <omp.h>
93 #endif
94
95 /* could enable at some point but for now there are far too many conversions */
96 #ifdef __GNUC__
97 #  pragma GCC diagnostic ignored "-Wdouble-promotion"
98 #endif
99
100 /* precalculated gaussian factors for 5x super sampling */
101 static const float gaussianFactors[5] = {
102     0.996849f,
103     0.596145f,
104     0.596145f,
105     0.596145f,
106     0.524141f};
107 static const float gaussianTotal = 3.309425f;
108
109 /* UV Image neighboring pixel table x and y list */
110 static int neighX[8] = {1, 1, 0, -1, -1, -1, 0, 1};
111 static int neighY[8] = {0, 1, 1, 1, 0, -1, -1, -1};
112
113 /* subframe_updateObject() flags */
114 #define SUBFRAME_RECURSION 5
115 #define UPDATE_MESH (1 << 1)
116 #define UPDATE_EVERYTHING (UPDATE_MESH) // | UPDATE_PARENTS
117 /* surface_getBrushFlags() return vals */
118 #define BRUSH_USES_VELOCITY (1 << 0)
119 /* brush mesh raycast status */
120 #define HIT_VOLUME 1
121 #define HIT_PROXIMITY 2
122 /* dynamicPaint_findNeighbourPixel() return codes */
123 #define NOT_FOUND -1
124 #define ON_MESH_EDGE -2
125 #define OUT_OF_TEXTURE -3
126 /* paint effect default movement per frame in global units */
127 #define EFF_MOVEMENT_PER_FRAME 0.05f
128 /* initial wave time factor */
129 #define WAVE_TIME_FAC (1.0f / 24.f)
130 #define CANVAS_REL_SIZE 5.0f
131 /* drying limits */
132 #define MIN_WETNESS 0.001f
133 #define MAX_WETNESS 5.0f
134
135
136 /* dissolve inline function */
137 BLI_INLINE void value_dissolve(float *r_value, const float time, const float scale, const int is_log)
138 {
139         *r_value = (is_log) ?
140                       (*r_value) * (powf(MIN_WETNESS, 1.0f / (1.2f * time / scale))) :
141                       (*r_value) - 1.0f / time * scale;
142 }
143
144
145 /***************************** Internal Structs ***************************/
146
147 typedef struct Bounds2D {
148         float min[2], max[2];
149 } Bounds2D;
150
151 typedef struct Bounds3D {
152         int valid;
153         float min[3], max[3];
154 } Bounds3D;
155
156 typedef struct VolumeGrid {
157         int dim[3];
158         Bounds3D grid_bounds; /* whole grid bounds */
159
160         Bounds3D *bounds;   /* (x*y*z) precalculated grid cell bounds */
161         int *s_pos; /* (x*y*z) t_index begin id */
162         int *s_num; /* (x*y*z) number of t_index points */
163         int *t_index; /* actual surface point index,
164                        * access: (s_pos+s_num) */
165 } VolumeGrid;
166
167 typedef struct Vec3f {
168         float v[3];
169 } Vec3f;
170
171 typedef struct BakeAdjPoint {
172         float dir[3];   /* vector pointing towards this neighbor */
173         float dist;     /* distance to */
174 } BakeAdjPoint;
175
176 /* Surface data used while processing a frame   */
177 typedef struct PaintBakeNormal {
178         float invNorm[3];  /* current pixel world-space inverted normal */
179         float normal_scale; /* normal directional scale for displace mapping */
180 } PaintBakeNormal;
181
182 /* Temp surface data used to process a frame */
183 typedef struct PaintBakeData {
184         /* point space data */
185         PaintBakeNormal *bNormal;
186         int *s_pos; /* index to start reading point sample realCoord */
187         int *s_num; /* num of realCoord samples */
188         Vec3f *realCoord;  /* current pixel center world-space coordinates for each sample
189                             *  ordered as (s_pos+s_num)*/
190         Bounds3D mesh_bounds;
191
192         /* adjacency info */
193         BakeAdjPoint *bNeighs; /* current global neighbor distances and directions, if required */
194         double average_dist;
195         /* space partitioning */
196         VolumeGrid *grid;       /* space partitioning grid to optimize brush checks */
197
198         /* velocity and movement */
199         Vec3f *velocity;        /* speed vector in global space movement per frame, if required */
200         Vec3f *prev_velocity;
201         float *brush_velocity;  /* special temp data for post-p velocity based brushes like smudge
202                                  *  3 float dir vec + 1 float str */
203         MVert *prev_verts;      /* copy of previous frame vertices. used to observe surface movement */
204         float prev_obmat[4][4]; /* previous frame object matrix */
205         int clear;              /* flag to check if surface was cleared/reset -> have to redo velocity etc. */
206
207 } PaintBakeData;
208
209 /* UV Image sequence format point       */
210 typedef struct PaintUVPoint {
211         /* Pixel / mesh data */
212         unsigned int face_index, pixel_index;   /* face index on domain derived mesh */
213         unsigned int v1, v2, v3;                /* vertex indexes */
214
215         unsigned int neighbour_pixel;   /* If this pixel isn't uv mapped to any face,
216                                          * but it's neighboring pixel is */
217         short quad;
218 } PaintUVPoint;
219
220 typedef struct ImgSeqFormatData {
221         PaintUVPoint *uv_p;
222         Vec3f *barycentricWeights;      /* b-weights for all pixel samples */
223 } ImgSeqFormatData;
224
225 /* adjacency data flags */
226 #define ADJ_ON_MESH_EDGE (1 << 0)
227
228 typedef struct PaintAdjData {
229         int *n_target;  /* array of neighboring point indexes,
230                          * for single sample use (n_index + neigh_num) */
231         int *n_index;   /* index to start reading n_target for each point */
232         int *n_num;     /* num of neighs for each point */
233         int *flags;     /* vertex adjacency flags */
234         int total_targets; /* size of n_target */
235 } PaintAdjData;
236
237 /***************************** General Utils ******************************/
238
239 /* Set canvas error string to display at the bake report */
240 static int setError(DynamicPaintCanvasSettings *canvas, const char *string)
241 {
242         /* Add error to canvas ui info label */
243         BLI_strncpy(canvas->error, string, sizeof(canvas->error));
244         return 0;
245 }
246
247 /* Get number of surface points for cached types */
248 static int dynamicPaint_surfaceNumOfPoints(DynamicPaintSurface *surface)
249 {
250         if (surface->format == MOD_DPAINT_SURFACE_F_PTEX) {
251                 return 0; /* not supported atm */
252         }
253         else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
254                 if (!surface->canvas->dm) return 0;  /* invalid derived mesh */
255                 return surface->canvas->dm->getNumVerts(surface->canvas->dm);
256         }
257         else
258                 return 0;
259 }
260
261 /* checks whether surface's format/type has realtime preview */
262 bool dynamicPaint_surfaceHasColorPreview(DynamicPaintSurface *surface)
263 {
264         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
265                 return 0;
266         }
267         else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
268                 if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE ||
269                     surface->type == MOD_DPAINT_SURFACE_T_WAVE)
270                 {
271                         return 0;
272                 }
273                 else {
274                         return 1;
275                 }
276         }
277         else {
278                 return 1;
279         }
280 }
281
282 /* get currently active surface (in user interface) */
283 DynamicPaintSurface *get_activeSurface(DynamicPaintCanvasSettings *canvas)
284 {
285         DynamicPaintSurface *surface = canvas->surfaces.first;
286         int i;
287
288         for (i = 0; surface; surface = surface->next) {
289                 if (i == canvas->active_sur)
290                         return surface;
291                 i++;
292         }
293         return NULL;
294 }
295
296 /* set preview to first previewable surface */
297 void dynamicPaint_resetPreview(DynamicPaintCanvasSettings *canvas)
298 {
299         DynamicPaintSurface *surface = canvas->surfaces.first;
300         int done = FALSE;
301
302         for (; surface; surface = surface->next) {
303                 if (!done && dynamicPaint_surfaceHasColorPreview(surface)) {
304                         surface->flags |= MOD_DPAINT_PREVIEW;
305                         done = TRUE;
306                 }
307                 else
308                         surface->flags &= ~MOD_DPAINT_PREVIEW;
309         }
310 }
311
312 /* set preview to defined surface */
313 static void dynamicPaint_setPreview(DynamicPaintSurface *t_surface)
314 {
315         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
316         for (; surface; surface = surface->next) {
317                 if (surface == t_surface)
318                         surface->flags |= MOD_DPAINT_PREVIEW;
319                 else
320                         surface->flags &= ~MOD_DPAINT_PREVIEW;
321         }
322 }
323
324 bool dynamicPaint_outputLayerExists(struct DynamicPaintSurface *surface, Object *ob, int output)
325 {
326         char *name;
327
328         if (output == 0)
329                 name = surface->output_name;
330         else if (output == 1)
331                 name = surface->output_name2;
332         else
333                 return 0;
334
335         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
336                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
337                         Mesh *me = ob->data;
338                         return (CustomData_get_named_layer_index(&me->fdata, CD_MCOL, name) != -1);
339                 }
340                 else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT)
341                         return (defgroup_name_index(ob, surface->output_name) != -1);
342         }
343
344         return 0;
345 }
346
347 static bool surface_duplicateOutputExists(void *arg, const char *name)
348 {
349         DynamicPaintSurface *t_surface = (DynamicPaintSurface *)arg;
350         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
351
352         for (; surface; surface = surface->next) {
353                 if (surface != t_surface && surface->type == t_surface->type &&
354                     surface->format == t_surface->format)
355                 {
356                         if (surface->output_name[0] != '\0' && !BLI_path_cmp(name, surface->output_name)) return true;
357                         if (surface->output_name2[0] != '\0' && !BLI_path_cmp(name, surface->output_name2)) return true;
358                 }
359         }
360         return false;
361 }
362
363 static void surface_setUniqueOutputName(DynamicPaintSurface *surface, char *basename, int output)
364 {
365         char name[64];
366         BLI_strncpy(name, basename, sizeof(name)); /* in case basename is surface->name use a copy */
367         if (!output)
368                 BLI_uniquename_cb(surface_duplicateOutputExists, surface, name, '.', surface->output_name, sizeof(surface->output_name));
369         if (output)
370                 BLI_uniquename_cb(surface_duplicateOutputExists, surface, name, '.', surface->output_name2, sizeof(surface->output_name2));
371 }
372
373
374 static bool surface_duplicateNameExists(void *arg, const char *name)
375 {
376         DynamicPaintSurface *t_surface = (DynamicPaintSurface *)arg;
377         DynamicPaintSurface *surface = t_surface->canvas->surfaces.first;
378
379         for (; surface; surface = surface->next) {
380                 if (surface != t_surface && !strcmp(name, surface->name)) return true;
381         }
382         return false;
383 }
384
385 void dynamicPaintSurface_setUniqueName(DynamicPaintSurface *surface, const char *basename)
386 {
387         char name[64];
388         BLI_strncpy(name, basename, sizeof(name)); /* in case basename is surface->name use a copy */
389         BLI_uniquename_cb(surface_duplicateNameExists, surface, name, '.', surface->name, sizeof(surface->name));
390 }
391
392
393 /* change surface data to defaults on new type */
394 void dynamicPaintSurface_updateType(struct DynamicPaintSurface *surface)
395 {
396         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
397                 surface->output_name[0] = '\0';
398                 surface->output_name2[0] = '\0';
399                 surface->flags |= MOD_DPAINT_ANTIALIAS;
400                 surface->depth_clamp = 1.0f;
401         }
402         else {
403                 strcpy(surface->output_name, "dp_");
404                 BLI_strncpy(surface->output_name2, surface->output_name, sizeof(surface->output_name2));
405                 surface->flags &= ~MOD_DPAINT_ANTIALIAS;
406                 surface->depth_clamp = 0.0f;
407         }
408
409         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
410                 strcat(surface->output_name, "paintmap");
411                 strcat(surface->output_name2, "wetmap");
412                 surface_setUniqueOutputName(surface, surface->output_name2, 1);
413         }
414         else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
415                 strcat(surface->output_name, "displace");
416         }
417         else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
418                 strcat(surface->output_name, "weight");
419         }
420         else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
421                 strcat(surface->output_name, "wave");
422         }
423
424         surface_setUniqueOutputName(surface, surface->output_name, 0);
425
426         /* update preview */
427         if (dynamicPaint_surfaceHasColorPreview(surface))
428                 dynamicPaint_setPreview(surface);
429         else
430                 dynamicPaint_resetPreview(surface->canvas);
431 }
432
433 static int surface_totalSamples(DynamicPaintSurface *surface)
434 {
435         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ &&
436             surface->flags & MOD_DPAINT_ANTIALIAS)
437         {
438                 return (surface->data->total_points * 5);
439         }
440         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX &&
441             surface->flags & MOD_DPAINT_ANTIALIAS && surface->data->adj_data)
442         {
443                 return (surface->data->total_points + surface->data->adj_data->total_targets);
444         }
445
446         return surface->data->total_points;
447 }
448
449 static void blendColors(const float t_color[3], float t_alpha, const float s_color[3], float s_alpha, float result[4])
450 {
451         int i;
452         float i_alpha = 1.0f - s_alpha;
453         float f_alpha = t_alpha * i_alpha + s_alpha;
454
455         /* blend colors */
456         if (f_alpha) {
457                 for (i = 0; i < 3; i++) {
458                         result[i] = (t_color[i] * t_alpha * i_alpha + s_color[i] * s_alpha) / f_alpha;
459                 }
460         }
461         else {
462                 copy_v3_v3(result, t_color);
463         }
464         /* return final alpha */
465         result[3] = f_alpha;
466 }
467
468 /* Mix two alpha weighed colors by a defined ratio. output is saved at a_color */
469 static float mixColors(float a_color[3], float a_weight, float b_color[3], float b_weight, float ratio)
470 {
471         float weight_ratio, factor;
472         if (b_weight) {
473                 /* if first value has no weight just use b_color */
474                 if (!a_weight) {
475                         copy_v3_v3(a_color, b_color);
476                         return b_weight * ratio;
477                 }
478                 weight_ratio = b_weight / (a_weight + b_weight);
479         }
480         else {
481                 return a_weight * (1.0f - ratio);
482         }
483
484         /* calculate final interpolation factor */
485         if (ratio <= 0.5f) {
486                 factor = weight_ratio * (ratio * 2.0f);
487         }
488         else {
489                 ratio = (ratio * 2.0f - 1.0f);
490                 factor = weight_ratio * (1.0f - ratio) + ratio;
491         }
492         /* mix final color */
493         interp_v3_v3v3(a_color, a_color, b_color, factor);
494         return (1.0f - factor) * a_weight + factor * b_weight;
495 }
496
497 /* set "ignore cache" flag for all caches on this object */
498 static void object_cacheIgnoreClear(Object *ob, int state)
499 {
500         ListBase pidlist;
501         PTCacheID *pid;
502         BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0);
503
504         for (pid = pidlist.first; pid; pid = pid->next) {
505                 if (pid->cache) {
506                         if (state)
507                                 pid->cache->flag |= PTCACHE_IGNORE_CLEAR;
508                         else
509                                 pid->cache->flag &= ~PTCACHE_IGNORE_CLEAR;
510                 }
511         }
512
513         BLI_freelistN(&pidlist);
514 }
515
516 static int subframe_updateObject(Scene *scene, Object *ob, int flags, int parent_recursion, float frame)
517 {
518         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint);
519         bConstraint *con;
520
521         /* if other is dynamic paint canvas, don't update */
522         if (pmd && pmd->canvas)
523                 return 1;
524
525         /* if object has parents, update them too */
526         if (parent_recursion) {
527                 int recursion = parent_recursion - 1;
528                 int is_canvas = 0;
529                 if (ob->parent) is_canvas += subframe_updateObject(scene, ob->parent, 0, recursion, frame);
530                 if (ob->track) is_canvas += subframe_updateObject(scene, ob->track, 0, recursion, frame);
531
532                 /* skip subframe if object is parented
533                  *  to vertex of a dynamic paint canvas */
534                 if (is_canvas && (ob->partype == PARVERT1 || ob->partype == PARVERT3))
535                         return 0;
536
537                 /* also update constraint targets */
538                 for (con = ob->constraints.first; con; con = con->next) {
539                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
540                         ListBase targets = {NULL, NULL};
541
542                         if (cti && cti->get_constraint_targets) {
543                                 bConstraintTarget *ct;
544                                 cti->get_constraint_targets(con, &targets);
545                                 for (ct = targets.first; ct; ct = ct->next) {
546                                         if (ct->tar)
547                                                 subframe_updateObject(scene, ct->tar, 0, recursion, frame);
548                                 }
549                                 /* free temp targets */
550                                 if (cti->flush_constraint_targets)
551                                         cti->flush_constraint_targets(con, &targets, 0);
552                         }
553                 }
554         }
555
556         /* was originally OB_RECALC_ALL - TODO - which flags are really needed??? */
557         ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
558         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, frame, ADT_RECALC_ANIM);
559         if (flags & UPDATE_MESH) {
560                 /* ignore cache clear during subframe updates
561                  *  to not mess up cache validity */
562                 object_cacheIgnoreClear(ob, 1);
563                 BKE_object_handle_update(G.main->eval_ctx, scene, ob);
564                 object_cacheIgnoreClear(ob, 0);
565         }
566         else
567                 BKE_object_where_is_calc_time(scene, ob, frame);
568
569         /* for curve following objects, parented curve has to be updated too */
570         if (ob->type == OB_CURVE) {
571                 Curve *cu = ob->data;
572                 BKE_animsys_evaluate_animdata(scene, &cu->id, cu->adt, frame, ADT_RECALC_ANIM);
573         }
574         /* and armatures... */
575         if (ob->type == OB_ARMATURE) {
576                 bArmature *arm = ob->data;
577                 BKE_animsys_evaluate_animdata(scene, &arm->id, arm->adt, frame, ADT_RECALC_ANIM);
578                 BKE_pose_where_is(scene, ob);
579         }
580
581         return 0;
582 }
583
584 static void scene_setSubframe(Scene *scene, float subframe)
585 {
586         /* dynamic paint subframes must be done on previous frame */
587         scene->r.cfra -= 1;
588         scene->r.subframe = subframe;
589 }
590
591 static int surface_getBrushFlags(DynamicPaintSurface *surface, Scene *scene)
592 {
593         Base *base = NULL;
594         GroupObject *go = NULL;
595         Object *brushObj = NULL;
596         ModifierData *md = NULL;
597
598         int flags = 0;
599
600         if (surface->brush_group)
601                 go = surface->brush_group->gobject.first;
602         else
603                 base = scene->base.first;
604
605         while (base || go) {
606                 brushObj = NULL;
607
608                 /* select object */
609                 if (surface->brush_group) {
610                         if (go->ob) brushObj = go->ob;
611                 }
612                 else
613                         brushObj = base->object;
614
615                 if (!brushObj) {
616                         if (surface->brush_group) go = go->next;
617                         else base = base->next;
618                         continue;
619                 }
620
621                 if (surface->brush_group)
622                         go = go->next;
623                 else
624                         base = base->next;
625
626                 md = modifiers_findByType(brushObj, eModifierType_DynamicPaint);
627                 if (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render)) {
628                         DynamicPaintModifierData *pmd2 = (DynamicPaintModifierData *)md;
629
630                         if (pmd2->brush) {
631                                 DynamicPaintBrushSettings *brush = pmd2->brush;
632
633                                 if (brush->flags & MOD_DPAINT_USES_VELOCITY)
634                                         flags |= BRUSH_USES_VELOCITY;
635                         }
636                 }
637         }
638
639         return flags;
640 }
641
642 static int brush_usesMaterial(DynamicPaintBrushSettings *brush, Scene *scene)
643 {
644         return ((brush->flags & MOD_DPAINT_USE_MATERIAL) && (!BKE_scene_use_new_shading_nodes(scene)));
645 }
646
647 /* check whether two bounds intersect */
648 static int boundsIntersect(Bounds3D *b1, Bounds3D *b2)
649 {
650         int i = 2;
651         if (!b1->valid || !b2->valid) return 0;
652         for (; i >= 0; i -= 1)
653                 if (!(b1->min[i] <= b2->max[i] && b1->max[i] >= b2->min[i])) return 0;
654         return 1;
655 }
656
657 /* check whether two bounds intersect inside defined proximity */
658 static int boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, float dist)
659 {
660         int i = 2;
661         if (!b1->valid || !b2->valid) return 0;
662         for (; i >= 0; i -= 1)
663                 if (!(b1->min[i] <= (b2->max[i] + dist) && b1->max[i] >= (b2->min[i] - dist))) return 0;
664         return 1;
665 }
666
667 /* check whether bounds intersects a point with given radius */
668 static int boundIntersectPoint(Bounds3D *b, float point[3], float radius)
669 {
670         int i = 2;
671         if (!b->valid) return 0;
672         for (; i >= 0; i -= 1)
673                 if (!(b->min[i] <= (point[i] + radius) && b->max[i] >= (point[i] - radius))) return 0;
674         return 1;
675 }
676
677 /* expand bounds by a new point */
678 static void boundInsert(Bounds3D *b, float point[3])
679 {
680         int i = 2;
681         if (!b->valid) {
682                 copy_v3_v3(b->min, point);
683                 copy_v3_v3(b->max, point);
684                 b->valid = 1;
685         }
686         else {
687                 for (; i >= 0; i -= 1) {
688                         if (point[i] < b->min[i]) b->min[i] = point[i];
689                         if (point[i] > b->max[i]) b->max[i] = point[i];
690                 }
691         }
692 }
693
694 static float getSurfaceDimension(PaintSurfaceData *sData)
695 {
696         Bounds3D *mb = &sData->bData->mesh_bounds;
697         return max_fff((mb->max[0] - mb->min[0]), (mb->max[1] - mb->min[1]), (mb->max[2] - mb->min[2]));
698 }
699
700 static void freeGrid(PaintSurfaceData *data)
701 {
702         PaintBakeData *bData = data->bData;
703         VolumeGrid *grid = bData->grid;
704
705         if (grid->bounds) MEM_freeN(grid->bounds);
706         if (grid->s_pos) MEM_freeN(grid->s_pos);
707         if (grid->s_num) MEM_freeN(grid->s_num);
708         if (grid->t_index) MEM_freeN(grid->t_index);
709
710         MEM_freeN(bData->grid);
711         bData->grid = NULL;
712 }
713
714 static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
715 {
716         PaintSurfaceData *sData = surface->data;
717         PaintBakeData *bData = sData->bData;
718         Bounds3D *grid_bounds;
719         VolumeGrid *grid;
720         int grid_cells, axis = 3;
721         int *temp_t_index = NULL;
722         int *temp_s_num = NULL;
723
724 #ifdef _OPENMP
725         int num_of_threads = omp_get_max_threads();
726 #else
727         int num_of_threads = 1;
728 #endif
729
730         if (bData->grid)
731                 freeGrid(sData);
732
733         /* allocate separate bounds for each thread */
734         grid_bounds = MEM_callocN(sizeof(Bounds3D) * num_of_threads, "Grid Bounds");
735         bData->grid = MEM_callocN(sizeof(VolumeGrid), "Surface Grid");
736         grid = bData->grid;
737
738         if (grid && grid_bounds) {
739                 int i, error = 0;
740                 float dim_factor, volume, dim[3];
741                 float td[3];
742                 float min_dim;
743
744                 /* calculate canvas dimensions */
745 #pragma omp parallel for schedule(static)
746                 for (i = 0; i < sData->total_points; i++) {
747 #ifdef _OPENMP
748                         int id = omp_get_thread_num();
749                         boundInsert(&grid_bounds[id], (bData->realCoord[bData->s_pos[i]].v));
750 #else
751                         boundInsert(&grid_bounds[0], (bData->realCoord[bData->s_pos[i]].v));
752 #endif
753                 }
754
755                 /* get final dimensions */
756                 for (i = 0; i < num_of_threads; i++) {
757                         boundInsert(&grid->grid_bounds, grid_bounds[i].min);
758                         boundInsert(&grid->grid_bounds, grid_bounds[i].max);
759                 }
760
761                 /* get dimensions */
762                 sub_v3_v3v3(dim, grid->grid_bounds.max, grid->grid_bounds.min);
763                 copy_v3_v3(td, dim);
764                 min_dim = max_fff(td[0], td[1], td[2]) / 1000.f;
765
766                 /* deactivate zero axises */
767                 for (i = 0; i < 3; i++) {
768                         if (td[i] < min_dim) { td[i] = 1.0f; axis -= 1; }
769                 }
770
771                 if (axis == 0 || max_fff(td[0], td[1], td[2]) < 0.0001f) {
772                         MEM_freeN(grid_bounds);
773                         MEM_freeN(bData->grid);
774                         bData->grid = NULL;
775                         return;
776                 }
777
778                 /* now calculate grid volume/area/width depending on num of active axis */
779                 volume = td[0] * td[1] * td[2];
780
781                 /* determine final grid size by trying to fit average 10.000 points per grid cell */
782                 dim_factor = (float)pow((double)volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis);
783
784                 /* define final grid size using dim_factor, use min 3 for active axises */
785                 for (i = 0; i < 3; i++) {
786                         grid->dim[i] = (int)floor(td[i] / dim_factor);
787                         CLAMP(grid->dim[i], (dim[i] >= min_dim) ? 3 : 1, 100);
788                 }
789                 grid_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
790
791                 /* allocate memory for grids */
792                 grid->bounds = MEM_callocN(sizeof(Bounds3D) * grid_cells, "Surface Grid Bounds");
793                 grid->s_pos = MEM_callocN(sizeof(int) * grid_cells, "Surface Grid Position");
794                 grid->s_num = MEM_callocN(sizeof(int) * grid_cells * num_of_threads, "Surface Grid Points");
795                 temp_s_num = MEM_callocN(sizeof(int) * grid_cells, "Temp Surface Grid Points");
796                 grid->t_index = MEM_callocN(sizeof(int) * sData->total_points, "Surface Grid Target Ids");
797                 temp_t_index = MEM_callocN(sizeof(int) * sData->total_points, "Temp Surface Grid Target Ids");
798
799                 /* in case of an allocation failure abort here */
800                 if (!grid->bounds || !grid->s_pos || !grid->s_num || !grid->t_index || !temp_s_num || !temp_t_index)
801                         error = 1;
802
803                 if (!error) {
804                         /* calculate number of points withing each cell */
805 #pragma omp parallel for schedule(static)
806                         for (i = 0; i < sData->total_points; i++) {
807                                 int co[3], j;
808                                 for (j = 0; j < 3; j++) {
809                                         co[j] = (int)floor((bData->realCoord[bData->s_pos[i]].v[j] - grid->grid_bounds.min[j]) / dim[j] * grid->dim[j]);
810                                         CLAMP(co[j], 0, grid->dim[j] - 1);
811                                 }
812
813                                 temp_t_index[i] = co[0] + co[1] * grid->dim[0] + co[2] * grid->dim[0] * grid->dim[1];
814 #ifdef _OPENMP
815                                 grid->s_num[temp_t_index[i] + omp_get_thread_num() * grid_cells]++;
816 #else
817                                 grid->s_num[temp_t_index[i]]++;
818 #endif
819                         }
820
821                         /* for first cell only calc s_num */
822                         for (i = 1; i < num_of_threads; i++) {
823                                 grid->s_num[0] += grid->s_num[i * grid_cells];
824                         }
825
826                         /* calculate grid indexes */
827                         for (i = 1; i < grid_cells; i++) {
828                                 int id;
829                                 for (id = 1; id < num_of_threads; id++) {
830                                         grid->s_num[i] += grid->s_num[i + id * grid_cells];
831                                 }
832                                 grid->s_pos[i] = grid->s_pos[i - 1] + grid->s_num[i - 1];
833                         }
834
835                         /* save point indexes to final array */
836                         for (i = 0; i < sData->total_points; i++) {
837                                 int pos = grid->s_pos[temp_t_index[i]] + temp_s_num[temp_t_index[i]];
838                                 grid->t_index[pos] = i;
839
840                                 temp_s_num[temp_t_index[i]]++;
841                         }
842
843                         /* calculate cell bounds */
844                         {
845                                 int x;
846 #pragma omp parallel for schedule(static)
847                                 for (x = 0; x < grid->dim[0]; x++) {
848                                         int y;
849                                         for (y = 0; y < grid->dim[1]; y++) {
850                                                 int z;
851                                                 for (z = 0; z < grid->dim[2]; z++) {
852                                                         int j, b_index = x + y * grid->dim[0] + z * grid->dim[0] * grid->dim[1];
853                                                         /* set bounds */
854                                                         for (j = 0; j < 3; j++) {
855                                                                 int s = (j == 0) ? x : ((j == 1) ? y : z);
856                                                                 grid->bounds[b_index].min[j] = grid->grid_bounds.min[j] + dim[j] / grid->dim[j] * s;
857                                                                 grid->bounds[b_index].max[j] = grid->grid_bounds.min[j] + dim[j] / grid->dim[j] * (s + 1);
858                                                         }
859                                                         grid->bounds[b_index].valid = 1;
860                                                 }
861                                         }
862                                 }
863                         }
864                 }
865
866                 if (temp_s_num) MEM_freeN(temp_s_num);
867                 if (temp_t_index) MEM_freeN(temp_t_index);
868
869                 /* free per thread s_num values */
870                 grid->s_num = MEM_reallocN(grid->s_num, sizeof(int) * grid_cells);
871
872                 if (error || !grid->s_num) {
873                         setError(surface->canvas, N_("Not enough free memory"));
874                         freeGrid(sData);
875                 }
876         }
877
878         if (grid_bounds) MEM_freeN(grid_bounds);
879 }
880
881 /***************************** Freeing data ******************************/
882
883 /* Free brush data */
884 void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd)
885 {
886         if (pmd->brush) {
887                 if (pmd->brush->dm)
888                         pmd->brush->dm->release(pmd->brush->dm);
889                 pmd->brush->dm = NULL;
890
891                 if (pmd->brush->paint_ramp)
892                         MEM_freeN(pmd->brush->paint_ramp);
893                 pmd->brush->paint_ramp = NULL;
894                 if (pmd->brush->vel_ramp)
895                         MEM_freeN(pmd->brush->vel_ramp);
896                 pmd->brush->vel_ramp = NULL;
897
898                 MEM_freeN(pmd->brush);
899                 pmd->brush = NULL;
900         }
901 }
902
903 static void dynamicPaint_freeAdjData(PaintSurfaceData *data)
904 {
905         if (data->adj_data) {
906                 if (data->adj_data->n_index) MEM_freeN(data->adj_data->n_index);
907                 if (data->adj_data->n_num) MEM_freeN(data->adj_data->n_num);
908                 if (data->adj_data->n_target) MEM_freeN(data->adj_data->n_target);
909                 if (data->adj_data->flags) MEM_freeN(data->adj_data->flags);
910                 MEM_freeN(data->adj_data);
911                 data->adj_data = NULL;
912         }
913 }
914
915 static void free_bakeData(PaintSurfaceData *data)
916 {
917         PaintBakeData *bData = data->bData;
918         if (bData) {
919                 if (bData->bNormal) MEM_freeN(bData->bNormal);
920                 if (bData->s_pos) MEM_freeN(bData->s_pos);
921                 if (bData->s_num) MEM_freeN(bData->s_num);
922                 if (bData->realCoord) MEM_freeN(bData->realCoord);
923                 if (bData->bNeighs) MEM_freeN(bData->bNeighs);
924                 if (bData->grid) freeGrid(data);
925                 if (bData->prev_verts) MEM_freeN(bData->prev_verts);
926                 if (bData->velocity) MEM_freeN(bData->velocity);
927                 if (bData->prev_velocity) MEM_freeN(bData->prev_velocity);
928
929                 MEM_freeN(data->bData);
930                 data->bData = NULL;
931         }
932 }
933
934 /* free surface data if it's not used anymore */
935 static void surface_freeUnusedData(DynamicPaintSurface *surface)
936 {
937         if (!surface->data) return;
938
939         /* free bakedata if not active or surface is baked */
940         if (!(surface->flags & MOD_DPAINT_ACTIVE) ||
941             (surface->pointcache && surface->pointcache->flag & PTCACHE_BAKED))
942         {
943                 free_bakeData(surface->data);
944         }
945 }
946
947 void dynamicPaint_freeSurfaceData(DynamicPaintSurface *surface)
948 {
949         PaintSurfaceData *data = surface->data;
950         if (!data) return;
951         if (data->format_data) {
952                 /* format specific free */
953                 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
954                         ImgSeqFormatData *format_data = (ImgSeqFormatData *)data->format_data;
955                         if (format_data->uv_p)
956                                 MEM_freeN(format_data->uv_p);
957                         if (format_data->barycentricWeights)
958                                 MEM_freeN(format_data->barycentricWeights);
959                 }
960                 MEM_freeN(data->format_data);
961         }
962         /* type data */
963         if (data->type_data) MEM_freeN(data->type_data);
964         dynamicPaint_freeAdjData(data);
965         /* bake data */
966         free_bakeData(data);
967
968         MEM_freeN(surface->data);
969         surface->data = NULL;
970 }
971
972 void dynamicPaint_freeSurface(DynamicPaintSurface *surface)
973 {
974         /* point cache */
975         BKE_ptcache_free_list(&(surface->ptcaches));
976         surface->pointcache = NULL;
977
978         if (surface->effector_weights)
979                 MEM_freeN(surface->effector_weights);
980         surface->effector_weights = NULL;
981
982         BLI_remlink(&(surface->canvas->surfaces), surface);
983         dynamicPaint_freeSurfaceData(surface);
984         MEM_freeN(surface);
985 }
986
987 /* Free canvas data */
988 void dynamicPaint_freeCanvas(DynamicPaintModifierData *pmd)
989 {
990         if (pmd->canvas) {
991                 /* Free surface data */
992                 DynamicPaintSurface *surface = pmd->canvas->surfaces.first;
993                 DynamicPaintSurface *next_surface = NULL;
994
995                 while (surface) {
996                         next_surface = surface->next;
997                         dynamicPaint_freeSurface(surface);
998                         surface = next_surface;
999                 }
1000
1001                 /* free dm copy */
1002                 if (pmd->canvas->dm)
1003                         pmd->canvas->dm->release(pmd->canvas->dm);
1004                 pmd->canvas->dm = NULL;
1005
1006                 MEM_freeN(pmd->canvas);
1007                 pmd->canvas = NULL;
1008         }
1009 }
1010
1011 /* Free whole dp modifier */
1012 void dynamicPaint_Modifier_free(struct DynamicPaintModifierData *pmd)
1013 {
1014         if (pmd) {
1015                 dynamicPaint_freeCanvas(pmd);
1016                 dynamicPaint_freeBrush(pmd);
1017         }
1018 }
1019
1020
1021 /***************************** Initialize and reset ******************************/
1022
1023 /*
1024  * Creates a new surface and adds it to the list
1025  * If scene is null, frame range of 1-250 is used
1026  * A pointer to this surface is returned
1027  */
1028 DynamicPaintSurface *dynamicPaint_createNewSurface(DynamicPaintCanvasSettings *canvas, Scene *scene)
1029 {
1030         DynamicPaintSurface *surface = MEM_callocN(sizeof(DynamicPaintSurface), "DynamicPaintSurface");
1031         if (!surface)
1032                 return NULL;
1033
1034         surface->canvas = canvas;
1035         surface->format = MOD_DPAINT_SURFACE_F_VERTEX;
1036         surface->type = MOD_DPAINT_SURFACE_T_PAINT;
1037
1038         /* cache */
1039         surface->pointcache = BKE_ptcache_add(&(surface->ptcaches));
1040         surface->pointcache->flag |= PTCACHE_DISK_CACHE;
1041         surface->pointcache->step = 1;
1042
1043         /* Set initial values */
1044         surface->flags = MOD_DPAINT_ANTIALIAS | MOD_DPAINT_MULALPHA | MOD_DPAINT_DRY_LOG | MOD_DPAINT_DISSOLVE_LOG |
1045                          MOD_DPAINT_ACTIVE | MOD_DPAINT_PREVIEW | MOD_DPAINT_OUT1 | MOD_DPAINT_USE_DRYING;
1046         surface->effect = 0;
1047         surface->effect_ui = 1;
1048
1049         surface->diss_speed = 250;
1050         surface->dry_speed = 500;
1051         surface->color_dry_threshold = 1.0f;
1052         surface->depth_clamp = 0.0f;
1053         surface->disp_factor = 1.0f;
1054         surface->disp_type = MOD_DPAINT_DISP_DISPLACE;
1055         surface->image_fileformat = MOD_DPAINT_IMGFORMAT_PNG;
1056
1057         surface->influence_scale = 1.0f;
1058         surface->radius_scale = 1.0f;
1059
1060         surface->init_color[0] = 1.0f;
1061         surface->init_color[1] = 1.0f;
1062         surface->init_color[2] = 1.0f;
1063         surface->init_color[3] = 1.0f;
1064
1065         surface->image_resolution = 256;
1066         surface->substeps = 0;
1067
1068         if (scene) {
1069                 surface->start_frame = scene->r.sfra;
1070                 surface->end_frame = scene->r.efra;
1071         }
1072         else {
1073                 surface->start_frame = 1;
1074                 surface->end_frame = 250;
1075         }
1076
1077         surface->spread_speed = 1.0f;
1078         surface->color_spread_speed = 1.0f;
1079         surface->shrink_speed = 1.0f;
1080
1081         surface->wave_damping = 0.04f;
1082         surface->wave_speed = 1.0f;
1083         surface->wave_timescale = 1.0f;
1084         surface->wave_spring = 0.20f;
1085         surface->wave_smoothness = 1.0f;
1086
1087         modifier_path_init(surface->image_output_path, sizeof(surface->image_output_path), "cache_dynamicpaint");
1088
1089         /* Using ID_BRUSH i18n context, as we have no physics/dpaint one for now... */
1090         dynamicPaintSurface_setUniqueName(surface, CTX_DATA_(BLF_I18NCONTEXT_ID_BRUSH, "Surface"));
1091
1092         surface->effector_weights = BKE_add_effector_weights(NULL);
1093
1094         dynamicPaintSurface_updateType(surface);
1095
1096         BLI_addtail(&canvas->surfaces, surface);
1097
1098         return surface;
1099 }
1100
1101 /*
1102  * Initialize modifier data
1103  */
1104 bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, struct Scene *scene)
1105 {
1106         if (pmd) {
1107                 if (type == MOD_DYNAMICPAINT_TYPE_CANVAS) {
1108                         DynamicPaintCanvasSettings *canvas;
1109                         if (pmd->canvas)
1110                                 dynamicPaint_freeCanvas(pmd);
1111
1112                         canvas = pmd->canvas = MEM_callocN(sizeof(DynamicPaintCanvasSettings), "DynamicPaint Canvas");
1113                         if (!canvas)
1114                                 return 0;
1115                         canvas->pmd = pmd;
1116                         canvas->dm = NULL;
1117
1118                         /* Create one surface */
1119                         if (!dynamicPaint_createNewSurface(canvas, scene))
1120                                 return 0;
1121
1122                 }
1123                 else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH) {
1124                         DynamicPaintBrushSettings *brush;
1125                         if (pmd->brush)
1126                                 dynamicPaint_freeBrush(pmd);
1127
1128                         brush = pmd->brush = MEM_callocN(sizeof(DynamicPaintBrushSettings), "DynamicPaint Paint");
1129                         if (!brush)
1130                                 return 0;
1131                         brush->pmd = pmd;
1132
1133                         brush->psys = NULL;
1134
1135                         brush->flags = MOD_DPAINT_ABS_ALPHA | MOD_DPAINT_RAMP_ALPHA;
1136                         brush->collision = MOD_DPAINT_COL_VOLUME;
1137                         
1138                         brush->mat = NULL;
1139                         brush->r = 0.15f;
1140                         brush->g = 0.4f;
1141                         brush->b = 0.8f;
1142                         brush->alpha = 1.0f;
1143                         brush->wetness = 1.0f;
1144
1145                         brush->paint_distance = 1.0f;
1146                         brush->proximity_falloff = MOD_DPAINT_PRFALL_SMOOTH;
1147
1148                         brush->particle_radius = 0.2f;
1149                         brush->particle_smooth = 0.05f;
1150
1151                         brush->wave_type = MOD_DPAINT_WAVEB_CHANGE;
1152                         brush->wave_factor = 1.0f;
1153                         brush->wave_clamp = 0.0f;
1154                         brush->smudge_strength = 0.3f;
1155                         brush->max_velocity = 1.0f;
1156
1157                         brush->dm = NULL;
1158
1159                         /* Paint proximity falloff colorramp. */
1160                         {
1161                                 CBData *ramp;
1162
1163                                 brush->paint_ramp = add_colorband(false);
1164                                 if (!brush->paint_ramp)
1165                                         return 0;
1166                                 ramp = brush->paint_ramp->data;
1167                                 /* Add default smooth-falloff ramp.     */
1168                                 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = 1.0f;
1169                                 ramp[0].pos = 0.0f;
1170                                 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].pos = 1.0f;
1171                                 ramp[1].a = 0.0f;
1172                                 pmd->brush->paint_ramp->tot = 2;
1173                         }
1174
1175                         /* Brush velocity ramp. */
1176                         {
1177                                 CBData *ramp;
1178
1179                                 brush->vel_ramp = add_colorband(false);
1180                                 if (!brush->vel_ramp)
1181                                         return 0;
1182                                 ramp = brush->vel_ramp->data;
1183                                 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = ramp[0].pos = 0.0f;
1184                                 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].a = ramp[1].pos = 1.0f;
1185                                 brush->paint_ramp->tot = 2;
1186                         }
1187                 }
1188         }
1189         else
1190                 return 0;
1191
1192         return 1;
1193 }
1194
1195 void dynamicPaint_Modifier_copy(struct DynamicPaintModifierData *pmd, struct DynamicPaintModifierData *tpmd)
1196 {
1197         /* Init modifier        */
1198         tpmd->type = pmd->type;
1199         if (pmd->canvas)
1200                 dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_CANVAS, NULL);
1201         if (pmd->brush)
1202                 dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_BRUSH, NULL);
1203
1204         /* Copy data    */
1205         if (tpmd->canvas) {
1206                 DynamicPaintSurface *surface;
1207                 tpmd->canvas->pmd = tpmd;
1208                 /* free default surface */
1209                 if (tpmd->canvas->surfaces.first)
1210                         dynamicPaint_freeSurface(tpmd->canvas->surfaces.first);
1211
1212                 /* copy existing surfaces */
1213                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1214                         DynamicPaintSurface *t_surface = dynamicPaint_createNewSurface(tpmd->canvas, NULL);
1215
1216                         /* surface settings */
1217                         t_surface->brush_group = surface->brush_group;
1218                         MEM_freeN(t_surface->effector_weights);
1219                         t_surface->effector_weights = MEM_dupallocN(surface->effector_weights);
1220
1221                         BLI_strncpy(t_surface->name, surface->name, sizeof(t_surface->name));
1222                         t_surface->format = surface->format;
1223                         t_surface->type = surface->type;
1224                         t_surface->disp_type = surface->disp_type;
1225                         t_surface->image_fileformat = surface->image_fileformat;
1226                         t_surface->effect_ui = surface->effect_ui;
1227                         t_surface->preview_id = surface->preview_id;
1228                         t_surface->init_color_type = surface->init_color_type;
1229                         t_surface->flags = surface->flags;
1230                         t_surface->effect = surface->effect;
1231
1232                         t_surface->image_resolution = surface->image_resolution;
1233                         t_surface->substeps = surface->substeps;
1234                         t_surface->start_frame = surface->start_frame;
1235                         t_surface->end_frame = surface->end_frame;
1236
1237                         copy_v4_v4(t_surface->init_color, surface->init_color);
1238                         t_surface->init_texture = surface->init_texture;
1239                         BLI_strncpy(t_surface->init_layername, surface->init_layername, sizeof(t_surface->init_layername));
1240
1241                         t_surface->dry_speed = surface->dry_speed;
1242                         t_surface->diss_speed = surface->diss_speed;
1243                         t_surface->color_dry_threshold = surface->color_dry_threshold;
1244                         t_surface->depth_clamp = surface->depth_clamp;
1245                         t_surface->disp_factor = surface->disp_factor;
1246
1247
1248                         t_surface->spread_speed = surface->spread_speed;
1249                         t_surface->color_spread_speed = surface->color_spread_speed;
1250                         t_surface->shrink_speed = surface->shrink_speed;
1251                         t_surface->drip_vel = surface->drip_vel;
1252                         t_surface->drip_acc = surface->drip_acc;
1253
1254                         t_surface->influence_scale = surface->influence_scale;
1255                         t_surface->radius_scale = surface->radius_scale;
1256
1257                         t_surface->wave_damping = surface->wave_damping;
1258                         t_surface->wave_speed = surface->wave_speed;
1259                         t_surface->wave_timescale = surface->wave_timescale;
1260                         t_surface->wave_spring = surface->wave_spring;
1261                         t_surface->wave_smoothness = surface->wave_smoothness;
1262
1263                         BLI_strncpy(t_surface->uvlayer_name, surface->uvlayer_name, sizeof(t_surface->uvlayer_name));
1264                         BLI_strncpy(t_surface->image_output_path, surface->image_output_path, sizeof(t_surface->image_output_path));
1265                         BLI_strncpy(t_surface->output_name, surface->output_name, sizeof(t_surface->output_name));
1266                         BLI_strncpy(t_surface->output_name2, surface->output_name2, sizeof(t_surface->output_name2));
1267                 }
1268                 dynamicPaint_resetPreview(tpmd->canvas);
1269         }
1270         else if (tpmd->brush) {
1271                 DynamicPaintBrushSettings *brush = pmd->brush, *t_brush = tpmd->brush;
1272                 t_brush->pmd = tpmd;
1273
1274                 t_brush->flags = brush->flags;
1275                 t_brush->collision = brush->collision;
1276
1277                 t_brush->mat = brush->mat;
1278                 t_brush->r = brush->r;
1279                 t_brush->g = brush->g;
1280                 t_brush->b = brush->b;
1281                 t_brush->alpha = brush->alpha;
1282                 t_brush->wetness = brush->wetness;
1283
1284                 t_brush->particle_radius = brush->particle_radius;
1285                 t_brush->particle_smooth = brush->particle_smooth;
1286                 t_brush->paint_distance = brush->paint_distance;
1287                 t_brush->psys = brush->psys;
1288
1289                 if (brush->paint_ramp)
1290                         memcpy(t_brush->paint_ramp, brush->paint_ramp, sizeof(ColorBand));
1291                 if (brush->vel_ramp)
1292                         memcpy(t_brush->vel_ramp, brush->vel_ramp, sizeof(ColorBand));
1293
1294                 t_brush->proximity_falloff = brush->proximity_falloff;
1295                 t_brush->wave_type = brush->wave_type;
1296                 t_brush->ray_dir = brush->ray_dir;
1297
1298                 t_brush->wave_factor = brush->wave_factor;
1299                 t_brush->wave_clamp = brush->wave_clamp;
1300                 t_brush->max_velocity = brush->max_velocity;
1301                 t_brush->smudge_strength = brush->smudge_strength;
1302         }
1303 }
1304
1305 /* allocates surface data depending on surface type */
1306 static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface)
1307 {
1308         PaintSurfaceData *sData = surface->data;
1309
1310         switch (surface->type) {
1311                 case MOD_DPAINT_SURFACE_T_PAINT:
1312                         sData->type_data = MEM_callocN(sizeof(PaintPoint) * sData->total_points, "DynamicPaintSurface Data");
1313                         break;
1314                 case MOD_DPAINT_SURFACE_T_DISPLACE:
1315                         sData->type_data = MEM_callocN(sizeof(float) * sData->total_points, "DynamicPaintSurface DepthData");
1316                         break;
1317                 case MOD_DPAINT_SURFACE_T_WEIGHT:
1318                         sData->type_data = MEM_callocN(sizeof(float) * sData->total_points, "DynamicPaintSurface WeightData");
1319                         break;
1320                 case MOD_DPAINT_SURFACE_T_WAVE:
1321                         sData->type_data = MEM_callocN(sizeof(PaintWavePoint) * sData->total_points, "DynamicPaintSurface WaveData");
1322                         break;
1323         }
1324
1325         if (sData->type_data == NULL) setError(surface->canvas, N_("Not enough free memory"));
1326 }
1327
1328 static int surface_usesAdjDistance(DynamicPaintSurface *surface)
1329 {
1330         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && surface->effect) return 1;
1331         if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) return 1;
1332         return 0;
1333 }
1334
1335 static int surface_usesAdjData(DynamicPaintSurface *surface)
1336 {
1337         if (surface_usesAdjDistance(surface)) return 1;
1338         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX &&
1339             surface->flags & MOD_DPAINT_ANTIALIAS)
1340         {
1341                 return 1;
1342         }
1343         else {
1344                 return 0;
1345         }
1346 }
1347
1348 /* initialize surface adjacency data */
1349 static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, int force_init)
1350 {
1351         PaintSurfaceData *sData = surface->data;
1352         DerivedMesh *dm = surface->canvas->dm;
1353         PaintAdjData *ad;
1354         int *temp_data;
1355         int neigh_points = 0;
1356
1357         if (!surface_usesAdjData(surface) && !force_init) return;
1358
1359         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1360                 /* For vertex format, neighbors are connected by edges */
1361                 neigh_points = 2 * dm->getNumEdges(dm);
1362         }
1363         else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ)
1364                 neigh_points = sData->total_points * 8;
1365
1366         if (!neigh_points) return;
1367
1368         /* allocate memory */
1369         ad = sData->adj_data = MEM_callocN(sizeof(PaintAdjData), "Surface Adj Data");
1370         if (!ad) return;
1371         ad->n_index = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Index");
1372         ad->n_num = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Counts");
1373         temp_data = MEM_callocN(sizeof(int) * sData->total_points, "Temp Adj Data");
1374         ad->n_target = MEM_callocN(sizeof(int) * neigh_points, "Surface Adj Targets");
1375         ad->flags = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Flags");
1376         ad->total_targets = neigh_points;
1377
1378         /* in case of allocation error, free memory */
1379         if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) {
1380                 dynamicPaint_freeAdjData(sData);
1381                 if (temp_data) MEM_freeN(temp_data);
1382                 setError(surface->canvas, N_("Not enough free memory"));
1383                 return;
1384         }
1385
1386         if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1387                 int i;
1388                 int n_pos;
1389
1390                 /* For vertex format, count every vertex that is connected by an edge */
1391                 int numOfEdges = dm->getNumEdges(dm);
1392                 int numOfPolys = dm->getNumPolys(dm);
1393                 struct MEdge *edge =  dm->getEdgeArray(dm);
1394                 struct MPoly *mpoly = dm->getPolyArray(dm);
1395                 struct MLoop *mloop = dm->getLoopArray(dm);
1396
1397                 /* count number of edges per vertex */
1398                 for (i = 0; i < numOfEdges; i++) {
1399                         ad->n_num[edge[i].v1]++;
1400                         ad->n_num[edge[i].v2]++;
1401
1402                         temp_data[edge[i].v1]++;
1403                         temp_data[edge[i].v2]++;
1404                 }
1405
1406                 /* also add number of vertices to temp_data
1407                  *  to locate points on "mesh edge" */
1408                 for (i = 0; i < numOfPolys; i++) {
1409                         int j = 0;
1410                         for (; j < mpoly[i].totloop; j++) {
1411                                 temp_data[mloop[mpoly[i].loopstart + j].v]++;
1412                         }
1413                 }
1414
1415                 /* now check if total number of edges+faces for
1416                  *  each vertex is even, if not -> vertex is on mesh edge */
1417                 for (i = 0; i < sData->total_points; i++) {
1418                         if ((temp_data[i] % 2) ||
1419                             (temp_data[i] < 4))
1420                         {
1421                                 ad->flags[i] |= ADJ_ON_MESH_EDGE;
1422                         }
1423
1424                         /* reset temp data */ 
1425                         temp_data[i] = 0;
1426                 }
1427
1428                 /* order n_index array */
1429                 n_pos = 0;
1430                 for (i = 0; i < sData->total_points; i++) {
1431                         ad->n_index[i] = n_pos;
1432                         n_pos += ad->n_num[i];
1433                 }
1434
1435                 /* and now add neighbor data using that info */
1436                 for (i = 0; i < numOfEdges; i++) {
1437                         /* first vertex */
1438                         int index = edge[i].v1;
1439                         n_pos = ad->n_index[index] + temp_data[index];
1440                         ad->n_target[n_pos] = edge[i].v2;
1441                         temp_data[index]++;
1442
1443                         /* second vertex */
1444                         index = edge[i].v2;
1445                         n_pos = ad->n_index[index] + temp_data[index];
1446                         ad->n_target[n_pos] = edge[i].v1;
1447                         temp_data[index]++;
1448                 }
1449         }
1450         else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1451                 /* for image sequences, only allocate memory.
1452                  *  bake initialization takes care of rest */
1453         }
1454
1455         MEM_freeN(temp_data);
1456 }
1457
1458 static void dynamicPaint_setInitialColor(Scene *scene, DynamicPaintSurface *surface)
1459 {
1460         PaintSurfaceData *sData = surface->data;
1461         PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1462         DerivedMesh *dm = surface->canvas->dm;
1463         int i;
1464         const bool scene_color_manage = BKE_scene_check_color_management_enabled(scene);
1465
1466         if (surface->type != MOD_DPAINT_SURFACE_T_PAINT)
1467                 return;
1468
1469         if (surface->init_color_type == MOD_DPAINT_INITIAL_NONE)
1470                 return;
1471         /* Single color */
1472         else if (surface->init_color_type == MOD_DPAINT_INITIAL_COLOR) {
1473                 /* apply color to every surface point */
1474 #pragma omp parallel for schedule(static)
1475                 for (i = 0; i < sData->total_points; i++) {
1476                         copy_v3_v3(pPoint[i].color, surface->init_color);
1477                         pPoint[i].alpha = surface->init_color[3];
1478                 }
1479         }
1480         /* UV mapped texture */
1481         else if (surface->init_color_type == MOD_DPAINT_INITIAL_TEXTURE) {
1482                 Tex *tex = surface->init_texture;
1483                 MTFace *tface;
1484                 MFace *mface = dm->getTessFaceArray(dm);
1485                 int numOfFaces = dm->getNumTessFaces(dm);
1486                 char uvname[MAX_CUSTOMDATA_LAYER_NAME];
1487
1488                 if (!tex) return;
1489
1490                 /* get uv map */
1491                 CustomData_validate_layer_name(&dm->faceData, CD_MTFACE, surface->init_layername, uvname);
1492                 tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
1493                 if (!tface) return;
1494
1495                 /* for vertex surface loop through tfaces and find uv color
1496                  *  that provides highest alpha */
1497                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1498                         struct ImagePool *pool = BKE_image_pool_new();
1499
1500 #pragma omp parallel for schedule(static) shared(pool)
1501                         for (i = 0; i < numOfFaces; i++) {
1502                                 int numOfVert = (mface[i].v4) ? 4 : 3;
1503                                 float uv[3] = {0.0f};
1504                                 int j;
1505                                 for (j = 0; j < numOfVert; j++) {
1506                                         TexResult texres = {0};
1507                                         unsigned int *vert = (&mface[i].v1) + j;
1508
1509                                         /* remap to -1.0 to 1.0 */
1510                                         uv[0] = tface[i].uv[j][0] * 2.0f - 1.0f;
1511                                         uv[1] = tface[i].uv[j][1] * 2.0f - 1.0f;
1512
1513                                         multitex_ext_safe(tex, uv, &texres, pool, scene_color_manage);
1514
1515                                         if (texres.tin > pPoint[*vert].alpha) {
1516                                                 copy_v3_v3(pPoint[*vert].color, &texres.tr);
1517                                                 pPoint[*vert].alpha = texres.tin;
1518                                         }
1519                                 }
1520                         }
1521                         BKE_image_pool_free(pool);
1522                 }
1523                 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1524                         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
1525                         int samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1526
1527 #pragma omp parallel for schedule(static)
1528                         for (i = 0; i < sData->total_points; i++) {
1529                                 float uv[9] = {0.0f};
1530                                 float uv_final[3] = {0.0f};
1531                                 int j;
1532                                 TexResult texres = {0};
1533
1534                                 /* collect all uvs */
1535                                 for (j = 0; j < 3; j++) {
1536                                         int v = (f_data->uv_p[i].quad && j > 0) ? j + 1 : j;
1537                                         copy_v2_v2(&uv[j * 3], tface[f_data->uv_p[i].face_index].uv[v]);
1538                                 }
1539
1540                                 /* interpolate final uv pos */
1541                                 interp_v3_v3v3v3(uv_final, &uv[0], &uv[3], &uv[6],
1542                                                  f_data->barycentricWeights[i * samples].v);
1543                                 /* remap to -1.0 to 1.0 */
1544                                 uv_final[0] = uv_final[0] * 2.0f - 1.0f;
1545                                 uv_final[1] = uv_final[1] * 2.0f - 1.0f;
1546
1547                                 multitex_ext_safe(tex, uv_final, &texres, NULL, scene_color_manage);
1548
1549                                 /* apply color */
1550                                 copy_v3_v3(pPoint[i].color, &texres.tr);
1551                                 pPoint[i].alpha = texres.tin;
1552                         }
1553                 }
1554         }
1555         /* vertex color layer */
1556         else if (surface->init_color_type == MOD_DPAINT_INITIAL_VERTEXCOLOR) {
1557
1558                 /* for vertex surface, just copy colors from mcol */
1559                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1560                         MLoop *mloop = dm->getLoopArray(dm);
1561                         int numOfLoops = dm->getNumLoops(dm);
1562                         MCol *col = CustomData_get_layer_named(&dm->loopData, CD_MLOOPCOL, surface->init_layername);
1563                         if (!col) return;
1564
1565 #pragma omp parallel for schedule(static)
1566                         for (i = 0; i < numOfLoops; i++) {
1567                                 pPoint[mloop[i].v].color[0] = 1.0f / 255.f * (float)col[i].b;
1568                                 pPoint[mloop[i].v].color[1] = 1.0f / 255.f * (float)col[i].g;
1569                                 pPoint[mloop[i].v].color[2] = 1.0f / 255.f * (float)col[i].r;
1570                                 pPoint[mloop[i].v].alpha = 1.0f / 255.f * (float)col[i].a;
1571                         }
1572                 }
1573                 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1574                         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
1575                         int samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1576                         MCol *col = CustomData_get_layer_named(&dm->faceData, CD_MCOL, surface->init_layername);
1577                         if (!col) return;
1578
1579 #pragma omp parallel for schedule(static)
1580                         for (i = 0; i < sData->total_points; i++) {
1581                                 int face_ind = f_data->uv_p[i].face_index;
1582                                 float colors[3][4] = {{0.0f, 0.0f, 0.0f, 0.0f}};
1583                                 float final_color[4];
1584                                 int j;
1585                                 /* collect color values */
1586                                 for (j = 0; j < 3; j++) {
1587                                         int v = (f_data->uv_p[i].quad && j > 0) ? j + 1 : j;
1588                                         colors[j][0] = 1.0f / 255.f * (float)col[face_ind * 4 + v].b;
1589                                         colors[j][1] = 1.0f / 255.f * (float)col[face_ind * 4 + v].g;
1590                                         colors[j][2] = 1.0f / 255.f * (float)col[face_ind * 4 + v].r;
1591                                         colors[j][3] = 1.0f / 255.f * (float)col[face_ind * 4 + v].a;
1592                                 }
1593                                 
1594                                 /* interpolate final color */
1595                                 interp_v4_v4v4v4(final_color, colors[0], colors[1], colors[2],
1596                                                  f_data->barycentricWeights[i * samples].v);
1597
1598                                 copy_v3_v3(pPoint[i].color, final_color);
1599                                 pPoint[i].alpha = final_color[3];
1600                         }
1601                 }
1602         }
1603 }
1604
1605 /* clears surface data back to zero */
1606 void dynamicPaint_clearSurface(Scene *scene, DynamicPaintSurface *surface)
1607 {
1608         PaintSurfaceData *sData = surface->data;
1609         if (sData && sData->type_data) {
1610                 unsigned int data_size;
1611
1612                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1613                         data_size = sizeof(PaintPoint);
1614                 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE)
1615                         data_size = sizeof(PaintWavePoint);
1616                 else
1617                         data_size = sizeof(float);
1618
1619                 memset(sData->type_data, 0, data_size * sData->total_points);
1620
1621                 /* set initial color */
1622                 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1623                         dynamicPaint_setInitialColor(scene, surface);
1624
1625                 if (sData->bData)
1626                         sData->bData->clear = 1;
1627         }
1628 }
1629
1630 /* completely (re)initializes surface (only for point cache types)*/
1631 bool dynamicPaint_resetSurface(Scene *scene, DynamicPaintSurface *surface)
1632 {
1633         int numOfPoints = dynamicPaint_surfaceNumOfPoints(surface);
1634         /* free existing data */
1635         if (surface->data) dynamicPaint_freeSurfaceData(surface);
1636
1637         /* don't reallocate for image sequence types. they get handled only on bake */
1638         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) return 1;
1639         if (numOfPoints < 1) return 0;
1640
1641         /* allocate memory */
1642         surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData");
1643         if (!surface->data) return 0;
1644
1645         /* allocate data depending on surface type and format */
1646         surface->data->total_points = numOfPoints;
1647         dynamicPaint_allocateSurfaceType(surface);
1648         dynamicPaint_initAdjacencyData(surface, 0);
1649
1650         /* set initial color */
1651         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT)
1652                 dynamicPaint_setInitialColor(scene, surface);
1653
1654         return 1;
1655 }
1656
1657 /* make sure allocated surface size matches current requirements */
1658 static bool dynamicPaint_checkSurfaceData(Scene *scene, DynamicPaintSurface *surface)
1659 {
1660         if (!surface->data || ((dynamicPaint_surfaceNumOfPoints(surface) != surface->data->total_points))) {
1661                 return dynamicPaint_resetSurface(scene, surface);
1662         }
1663         return 1;
1664 }
1665
1666
1667 /***************************** Modifier processing ******************************/
1668
1669
1670 /* apply displacing vertex surface to the derived mesh */
1671 static void dynamicPaint_applySurfaceDisplace(DynamicPaintSurface *surface, DerivedMesh *result)
1672 {
1673         PaintSurfaceData *sData = surface->data;
1674
1675         if (!sData || surface->format != MOD_DPAINT_SURFACE_F_VERTEX) return;
1676
1677         /* displace paint */
1678         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
1679                 MVert *mvert = result->getVertArray(result);
1680                 int i;
1681                 float *value = (float *)sData->type_data;
1682
1683 #pragma omp parallel for schedule(static)
1684                 for (i = 0; i < sData->total_points; i++) {
1685                         float normal[3], val = value[i] * surface->disp_factor;
1686                         normal_short_to_float_v3(normal, mvert[i].no);
1687                         normalize_v3(normal);
1688
1689                         mvert[i].co[0] -= normal[0] * val;
1690                         mvert[i].co[1] -= normal[1] * val;
1691                         mvert[i].co[2] -= normal[2] * val;
1692                 }
1693         }
1694 }
1695
1696 /*
1697  *      Apply canvas data to the object derived mesh
1698  */
1699 static DerivedMesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd,
1700                                                 Object *ob,
1701                                                 DerivedMesh *dm)
1702 {
1703         DerivedMesh *result = CDDM_copy(dm);
1704
1705         if (pmd->canvas && !(pmd->canvas->flags & MOD_DPAINT_BAKING)) {
1706
1707                 DynamicPaintSurface *surface;
1708                 bool update_normals = false;
1709
1710                 /* loop through surfaces */
1711                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1712                         PaintSurfaceData *sData = surface->data;
1713
1714                         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && sData) {
1715                                 if (!(surface->flags & (MOD_DPAINT_ACTIVE))) continue;
1716
1717                                 /* process vertex surface previews */
1718                                 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1719
1720                                         /* vertex color paint */
1721                                         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1722
1723                                                 int i;
1724                                                 PaintPoint *pPoint = (PaintPoint *)sData->type_data;
1725                                                 MLoopCol *col = NULL;
1726                                                 MLoop *mloop = CDDM_get_loops(result);
1727                                                 int totloop = result->numLoopData;
1728
1729                                                 /* paint is stored on dry and wet layers, so mix final color first */
1730                                                 float *fcolor = MEM_callocN(sizeof(float) * sData->total_points * 4, "Temp paint color");
1731
1732 #pragma omp parallel for schedule(static)
1733                                                 for (i = 0; i < sData->total_points; i++) {
1734                                                         /* blend dry and wet layer */
1735                                                         blendColors(pPoint[i].color, pPoint[i].alpha, pPoint[i].e_color, pPoint[i].e_alpha, &fcolor[i * 4]);
1736                                                 }
1737
1738                                                 /* viewport preview */
1739                                                 if (surface->flags & MOD_DPAINT_PREVIEW) {
1740                                                         MPoly *mp = CDDM_get_polys(result);
1741                                                         int totpoly = result->numPolyData;
1742
1743 #if 0
1744                                                         /* XXX We have to create a CD_PREVIEW_MCOL, else it might sigsev
1745                                                          *     (after a SubSurf mod, eg)... */
1746                                                         if (!result->getTessFaceDataArray(result, CD_PREVIEW_MCOL)) {
1747                                                                 int numFaces = result->getNumTessFaces(result);
1748                                                                 CustomData_add_layer(&result->faceData, CD_PREVIEW_MCOL, CD_CALLOC, NULL, numFaces);
1749                                                         }
1750 #endif
1751
1752                                                         /* Save preview results to weight layer to be
1753                                                          *   able to share same drawing methods */
1754                                                         col = CustomData_get_layer(&result->loopData, CD_PREVIEW_MLOOPCOL);
1755                                                         if (!col)
1756                                                                 col = CustomData_add_layer(&result->loopData, CD_PREVIEW_MLOOPCOL, CD_CALLOC,
1757                                                                                            NULL, totloop);
1758
1759                                                         if (col) {
1760 #pragma omp parallel for schedule(static)
1761                                                                 for (i = 0; i < totpoly; i++) {
1762                                                                         int j = 0;
1763                                                                         Material *material = give_current_material(ob, mp[i].mat_nr + 1);
1764
1765                                                                         for (; j < mp[i].totloop; j++) {
1766                                                                                 int l_index = mp[i].loopstart + j;
1767                                                                                 int v_index = mloop[l_index].v;
1768
1769                                                                                 if (surface->preview_id == MOD_DPAINT_SURFACE_PREV_PAINT) {
1770                                                                                         float c[3];
1771                                                                                         v_index *= 4;
1772
1773                                                                                         /* Apply material color as base vertex color for preview */
1774                                                                                         col[l_index].a = 255;
1775                                                                                         if (material) {
1776                                                                                                 c[0] = material->r;
1777                                                                                                 c[1] = material->g;
1778                                                                                                 c[2] = material->b;
1779                                                                                         }
1780                                                                                         else { /* default gray */
1781                                                                                                 c[0] = 0.65f;
1782                                                                                                 c[1] = 0.65f;
1783                                                                                                 c[2] = 0.65f;
1784                                                                                         }
1785                                                                                         /* mix surface color */
1786                                                                                         interp_v3_v3v3(c, c, &fcolor[v_index], fcolor[v_index + 3]);
1787
1788                                                                                         rgb_float_to_uchar((unsigned char *)&col[l_index].r, c);
1789                                                                                 }
1790                                                                                 else {
1791                                                                                         col[l_index].r =
1792                                                                                             col[l_index].g =
1793                                                                                                 col[l_index].b = FTOCHAR(pPoint[v_index].wetness);
1794                                                                                         col[l_index].a = 255;
1795                                                                                 }
1796                                                                         }
1797                                                                 }
1798                                                         }
1799                                                 }
1800
1801
1802                                                 /* save layer data to output layer */
1803
1804                                                 /* paint layer */
1805                                                 col = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, surface->output_name);
1806                                                 /* if output layer is lost from a constructive modifier, re-add it */
1807                                                 if (!col && dynamicPaint_outputLayerExists(surface, ob, 0))
1808                                                         col = CustomData_add_layer_named(&result->loopData, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, surface->output_name);
1809                                                 /* apply color */
1810                                                 if (col) {
1811 #pragma omp parallel for schedule(static)
1812                                                         for (i = 0; i < totloop; i++) {
1813                                                                 int index = mloop[i].v * 4;
1814                                                                 rgb_float_to_uchar((unsigned char *)&col[i].r, &fcolor[index]);
1815                                                                 col[i].a = FTOCHAR(fcolor[index + 3]); /* IS THIS NEEDED? */
1816                                                         }
1817                                                 }
1818                                                 
1819                                                 MEM_freeN(fcolor);
1820
1821                                                 /* wet layer */
1822                                                 col = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, surface->output_name2);
1823                                                 /* if output layer is lost from a constructive modifier, re-add it */
1824                                                 if (!col && dynamicPaint_outputLayerExists(surface, ob, 1))
1825                                                         col = CustomData_add_layer_named(&result->loopData, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, surface->output_name2);
1826                                                 /* apply color */
1827                                                 if (col) {
1828 #pragma omp parallel for schedule(static)
1829                                                         for (i = 0; i < totloop; i++) {
1830                                                                 int index = mloop[i].v;
1831                                                                 col[i].r =
1832                                                                     col[i].g =
1833                                                                         col[i].b = FTOCHAR(pPoint[index].wetness);
1834                                                                 col[i].a = 255;
1835                                                         }
1836                                                 }
1837
1838                                                 /* Mark tessellated CD layers as dirty. */
1839                                                 result->dirty |= DM_DIRTY_TESS_CDLAYERS;
1840                                         }
1841                                         /* vertex group paint */
1842                                         else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
1843                                                 int defgrp_index = defgroup_name_index(ob, surface->output_name);
1844                                                 MDeformVert *dvert = result->getVertDataArray(result, CD_MDEFORMVERT);
1845                                                 float *weight = (float *)sData->type_data;
1846
1847                                                 /* viewport preview */
1848                                                 if (surface->flags & MOD_DPAINT_PREVIEW) {
1849                                                         /* Save preview results to weight layer to be
1850                                                          * able to share same drawing methods.
1851                                                          * Note this func also sets DM_DIRTY_TESS_CDLAYERS flag! */
1852                                                         DM_update_weight_mcol(ob, result, 0, weight, 0, NULL);
1853                                                 }
1854
1855                                                 /* apply weights into a vertex group, if doesnt exists add a new layer */
1856                                                 if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0'))
1857                                                         dvert = CustomData_add_layer_named(&result->vertData, CD_MDEFORMVERT, CD_CALLOC,
1858                                                                                            NULL, sData->total_points, surface->output_name);
1859                                                 if (defgrp_index != -1 && dvert) {
1860                                                         int i;
1861                                                         for (i = 0; i < sData->total_points; i++) {
1862                                                                 MDeformVert *dv = &dvert[i];
1863                                                                 MDeformWeight *def_weight = defvert_find_index(dv, defgrp_index);
1864
1865                                                                 /* skip if weight value is 0 and no existing weight is found */
1866                                                                 if ((def_weight != NULL) || (weight[i] != 0.0f)) {
1867
1868                                                                         /* if not found, add a weight for it */
1869                                                                         if (def_weight == NULL) {
1870                                                                                 def_weight = defvert_verify_index(dv, defgrp_index);
1871                                                                         }
1872
1873                                                                         /* set weight value */
1874                                                                         def_weight->weight = weight[i];
1875                                                                 }
1876                                                         }
1877                                                 }
1878                                         }
1879                                         /* wave simulation */
1880                                         else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
1881                                                 MVert *mvert = result->getVertArray(result);
1882                                                 int i;
1883                                                 PaintWavePoint *wPoint = (PaintWavePoint *)sData->type_data;
1884
1885 #pragma omp parallel for schedule(static)
1886                                                 for (i = 0; i < sData->total_points; i++) {
1887                                                         float normal[3];
1888                                                         normal_short_to_float_v3(normal, mvert[i].no);
1889                                                         madd_v3_v3fl(mvert[i].co, normal, wPoint[i].height);
1890                                                 }
1891                                                 update_normals = true;
1892                                         }
1893
1894                                         /* displace */
1895                                         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
1896                                                 dynamicPaint_applySurfaceDisplace(surface, result);
1897                                                 update_normals = true;
1898                                         }
1899                                 }
1900                         }
1901                 }
1902
1903                 if (update_normals) {
1904                         result->dirty |= DM_DIRTY_NORMALS;
1905                 }
1906         }
1907         /* make a copy of dm to use as brush data */
1908         if (pmd->brush) {
1909                 if (pmd->brush->dm) pmd->brush->dm->release(pmd->brush->dm);
1910                 pmd->brush->dm = CDDM_copy(result);
1911         }
1912
1913         return result;
1914 }
1915
1916 /* update cache frame range */
1917 void dynamicPaint_cacheUpdateFrames(DynamicPaintSurface *surface)
1918 {
1919         if (surface->pointcache) {
1920                 surface->pointcache->startframe = surface->start_frame;
1921                 surface->pointcache->endframe = surface->end_frame;
1922         }
1923 }
1924
1925 static void canvas_copyDerivedMesh(DynamicPaintCanvasSettings *canvas, DerivedMesh *dm)
1926 {
1927         if (canvas->dm) {
1928                 canvas->dm->release(canvas->dm);
1929         }
1930
1931         canvas->dm = CDDM_copy(dm);
1932 }
1933
1934 /*
1935  *      Updates derived mesh copy and processes dynamic paint step / caches.
1936  */
1937 static void dynamicPaint_frameUpdate(DynamicPaintModifierData *pmd, Scene *scene, Object *ob, DerivedMesh *dm)
1938 {
1939         if (pmd->canvas) {
1940                 DynamicPaintCanvasSettings *canvas = pmd->canvas;
1941                 DynamicPaintSurface *surface = canvas->surfaces.first;
1942
1943                 /* update derived mesh copy */
1944                 canvas_copyDerivedMesh(canvas, dm);
1945
1946                 /* in case image sequence baking, stop here */
1947                 if (canvas->flags & MOD_DPAINT_BAKING) return;
1948
1949                 /* loop through surfaces */
1950                 for (; surface; surface = surface->next) {
1951                         int current_frame = (int)scene->r.cfra;
1952                         bool no_surface_data;
1953
1954                         /* free bake data if not required anymore */
1955                         surface_freeUnusedData(surface);
1956
1957                         /* image sequences are handled by bake operator */
1958                         if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) continue;
1959                         if (!(surface->flags & MOD_DPAINT_ACTIVE)) continue;
1960
1961                         /* make sure surface is valid */
1962                         no_surface_data = surface->data == NULL;
1963                         if (!dynamicPaint_checkSurfaceData(scene, surface)) continue;
1964
1965                         /* limit frame range */
1966                         CLAMP(current_frame, surface->start_frame, surface->end_frame);
1967
1968                         if (no_surface_data || current_frame != surface->current_frame || (int)scene->r.cfra == surface->start_frame) {
1969                                 PointCache *cache = surface->pointcache;
1970                                 PTCacheID pid;
1971                                 surface->current_frame = current_frame;
1972
1973                                 /* read point cache */
1974                                 BKE_ptcache_id_from_dynamicpaint(&pid, ob, surface);
1975                                 pid.cache->startframe = surface->start_frame;
1976                                 pid.cache->endframe = surface->end_frame;
1977                                 BKE_ptcache_id_time(&pid, scene, (float)scene->r.cfra, NULL, NULL, NULL);
1978
1979                                 /* reset non-baked cache at first frame */
1980                                 if ((int)scene->r.cfra == surface->start_frame && !(cache->flag & PTCACHE_BAKED)) {
1981                                         cache->flag |= PTCACHE_REDO_NEEDED;
1982                                         BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
1983                                         cache->flag &= ~PTCACHE_REDO_NEEDED;
1984                                 }
1985
1986                                 /* try to read from cache */
1987                                 if (BKE_ptcache_read(&pid, (float)scene->r.cfra)) {
1988                                         BKE_ptcache_validate(cache, (int)scene->r.cfra);
1989                                 }
1990                                 /* if read failed and we're on surface range do recalculate */
1991                                 else if ((int)scene->r.cfra == current_frame && !(cache->flag & PTCACHE_BAKED)) {
1992                                         /* calculate surface frame */
1993                                         canvas->flags |= MOD_DPAINT_BAKING;
1994                                         dynamicPaint_calculateFrame(surface, scene, ob, current_frame);
1995                                         canvas->flags &= ~MOD_DPAINT_BAKING;
1996
1997                                         /* restore canvas derivedmesh if required */
1998                                         if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE &&
1999                                             surface->flags & MOD_DPAINT_DISP_INCREMENTAL && surface->next)
2000                                         {
2001                                                 canvas_copyDerivedMesh(canvas, dm);
2002                                         }
2003
2004                                         BKE_ptcache_validate(cache, surface->current_frame);
2005                                         BKE_ptcache_write(&pid, surface->current_frame);
2006                                 }
2007                         }
2008                 }
2009         }
2010 }
2011
2012 /* Modifier call. Processes dynamic paint modifier step. */
2013 DerivedMesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, Scene *scene, Object *ob, DerivedMesh *dm)
2014 {
2015         /* For now generate tessfaces in every case
2016          *  XXX - move/remove when most of dpaint functions are converted to use bmesh types */
2017         DM_ensure_tessface(dm);
2018
2019         /* Update canvas data for a new frame */
2020         dynamicPaint_frameUpdate(pmd, scene, ob, dm);
2021
2022         /* Return output mesh */
2023         return dynamicPaint_Modifier_apply(pmd, ob, dm);
2024 }
2025
2026
2027 /***************************** Image Sequence / UV Image Surface Calls ******************************/
2028
2029 /*
2030  *      Tries to find the neighboring pixel in given (uv space) direction.
2031  *      Result is used by effect system to move paint on the surface.
2032  *
2033  *   px, py : origin pixel x and y
2034  *      n_index : lookup direction index (use neighX, neighY to get final index)
2035  */
2036 static int dynamicPaint_findNeighbourPixel(PaintUVPoint *tempPoints, DerivedMesh *dm,
2037                                            const char *uvname, int w, int h, int px, int py, int n_index)
2038 {
2039         /* Note: Current method only uses polygon edges to detect neighboring pixels.
2040          *  -> It doesn't always lead to the optimum pixel but is accurate enough
2041          *  and faster/simpler than including possible face tip point links)
2042          */
2043
2044         int x, y;
2045         PaintUVPoint *tPoint = NULL;
2046         PaintUVPoint *cPoint = NULL;
2047
2048         /* shift position by given n_index */
2049         x = px + neighX[n_index];
2050         y = py + neighY[n_index];
2051
2052         if (x < 0 || x >= w) return OUT_OF_TEXTURE;
2053         if (y < 0 || y >= h) return OUT_OF_TEXTURE;
2054
2055         tPoint = &tempPoints[x + w * y];        /* UV neighbor */
2056         cPoint = &tempPoints[px + w * py];      /* Origin point */
2057
2058         /*
2059          *      Check if shifted point is on same face -> it's a correct neighbor
2060          *   (and if it isn't marked as an "edge pixel")
2061          */
2062         if ((tPoint->face_index == cPoint->face_index) && (tPoint->neighbour_pixel == -1))
2063                 return (x + w * y);
2064
2065         /*
2066          *      Even if shifted point is on another face
2067          *      -> use this point.
2068          *
2069          *      !! Replace with "is uv faces linked" check !!
2070          *      This should work fine as long as uv island
2071          *      margin is > 1 pixel.
2072          */
2073         if ((tPoint->face_index != -1) && (tPoint->neighbour_pixel == -1)) {
2074                 return (x + w * y);
2075         }
2076
2077         /*
2078          *      If we get here, the actual neighboring pixel
2079          *      is located on a non-linked uv face, and we have to find
2080          *      it's "real" position.
2081          *
2082          *      Simple neighboring face finding algorithm:
2083          *      - find closest uv edge to shifted pixel and get
2084          *        the another face that shares that edge
2085          *      - find corresponding position of that new face edge
2086          *        in uv space
2087          *
2088          *      TODO: Implement something more accurate / optimized?
2089          */
2090         {
2091                 int numOfFaces = dm->getNumTessFaces(dm);
2092                 MFace *mface = dm->getTessFaceArray(dm);
2093                 MTFace *tface =  CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
2094
2095                 /* Get closest edge to that subpixel on UV map  */
2096                 {
2097                         float pixel[2];
2098                         /* distances only used for comparison */
2099                         float dist_squared, t_dist_squared;
2100
2101                         int i, uindex[3], edge1_index, edge2_index,
2102                             e1_index, e2_index, target_face;
2103                         float closest_point[2], lambda, dir_vec[2];
2104                         int target_uv1, target_uv2, final_pixel[2], final_index;
2105
2106                         float *s_uv1, *s_uv2, *t_uv1, *t_uv2;
2107
2108                         pixel[0] = ((float)(px + neighX[n_index]) + 0.5f) / (float)w;
2109                         pixel[1] = ((float)(py + neighY[n_index]) + 0.5f) / (float)h;
2110
2111                         /* Get uv indexes for current face part */
2112                         if (cPoint->quad) {
2113                                 uindex[0] = 0; uindex[1] = 2; uindex[2] = 3;
2114                         }
2115                         else {
2116                                 uindex[0] = 0; uindex[1] = 1; uindex[2] = 2;
2117                         }
2118
2119                         /*
2120                          *      Find closest edge to that pixel
2121                          */
2122                         /* Dist to first edge */
2123                         e1_index = cPoint->v1; e2_index = cPoint->v2; edge1_index = uindex[0]; edge2_index = uindex[1];
2124                         dist_squared = dist_squared_to_line_segment_v2(pixel, tface[cPoint->face_index].uv[edge1_index], tface[cPoint->face_index].uv[edge2_index]);
2125
2126                         /* Dist to second edge */
2127                         t_dist_squared = dist_squared_to_line_segment_v2(pixel, tface[cPoint->face_index].uv[uindex[1]], tface[cPoint->face_index].uv[uindex[2]]);
2128                         if (t_dist_squared < dist_squared) { e1_index = cPoint->v2; e2_index = cPoint->v3; edge1_index = uindex[1]; edge2_index = uindex[2]; dist_squared = t_dist_squared; }
2129
2130                         /* Dist to third edge */
2131                         t_dist_squared = dist_squared_to_line_segment_v2(pixel, tface[cPoint->face_index].uv[uindex[2]], tface[cPoint->face_index].uv[uindex[0]]);
2132                         if (t_dist_squared < dist_squared) { e1_index = cPoint->v3; e2_index = cPoint->v1;  edge1_index = uindex[2]; edge2_index = uindex[0]; dist_squared = t_dist_squared; }
2133
2134
2135                         /*
2136                          *      Now find another face that is linked to that edge
2137                          */
2138                         target_face = -1;
2139
2140                         for (i = 0; i < numOfFaces; i++) {
2141                                 /*
2142                                  *      Check if both edge vertices share this face
2143                                  */
2144                                 int v4 = (mface[i].v4) ? mface[i].v4 : -1;
2145
2146                                 if ((e1_index == mface[i].v1 || e1_index == mface[i].v2 || e1_index == mface[i].v3 || e1_index == v4) &&
2147                                     (e2_index == mface[i].v1 || e2_index == mface[i].v2 || e2_index == mface[i].v3 || e2_index == v4))
2148                                 {
2149                                         if (i == cPoint->face_index) continue;
2150
2151                                         target_face = i;
2152
2153                                         /*
2154                                          *      Get edge UV index
2155                                          */
2156                                         if (e1_index == mface[i].v1) target_uv1 = 0;
2157                                         else if (e1_index == mface[i].v2) target_uv1 = 1;
2158                                         else if (e1_index == mface[i].v3) target_uv1 = 2;
2159                                         else target_uv1 = 3;
2160
2161                                         if (e2_index == mface[i].v1) target_uv2 = 0;
2162                                         else if (e2_index == mface[i].v2) target_uv2 = 1;
2163                                         else if (e2_index == mface[i].v3) target_uv2 = 2;
2164                                         else target_uv2 = 3;
2165
2166                                         break;
2167                                 }
2168                         }
2169
2170                         /* If none found pixel is on mesh edge  */
2171                         if (target_face == -1) return ON_MESH_EDGE;
2172
2173                         /*
2174                          *      If target face is connected in UV space as well, just use original index
2175                          */
2176                         s_uv1 = (float *)tface[cPoint->face_index].uv[edge1_index];
2177                         s_uv2 = (float *)tface[cPoint->face_index].uv[edge2_index];
2178                         t_uv1 = (float *)tface[target_face].uv[target_uv1];
2179                         t_uv2 = (float *)tface[target_face].uv[target_uv2];
2180
2181                         //printf("connected UV : %f,%f & %f,%f - %f,%f & %f,%f\n", s_uv1[0], s_uv1[1], s_uv2[0], s_uv2[1], t_uv1[0], t_uv1[1], t_uv2[0], t_uv2[1]);
2182
2183                         if (((s_uv1[0] == t_uv1[0] && s_uv1[1] == t_uv1[1]) &&
2184                              (s_uv2[0] == t_uv2[0] && s_uv2[1] == t_uv2[1]) ) ||
2185                             ((s_uv2[0] == t_uv1[0] && s_uv2[1] == t_uv1[1]) &&
2186                              (s_uv1[0] == t_uv2[0] && s_uv1[1] == t_uv2[1]) ))
2187                         {
2188                                 return ((px + neighX[n_index]) + w * (py + neighY[n_index]));
2189                         }
2190
2191                         /*
2192                          *      Find a point that is relatively at same edge position
2193                          *      on this other face UV
2194                          */
2195                         lambda = closest_to_line_v2(closest_point, pixel, tface[cPoint->face_index].uv[edge1_index], tface[cPoint->face_index].uv[edge2_index]);
2196                         if (lambda < 0.0f) lambda = 0.0f;
2197                         if (lambda > 1.0f) lambda = 1.0f;
2198
2199                         sub_v2_v2v2(dir_vec, tface[target_face].uv[target_uv2], tface[target_face].uv[target_uv1]);
2200
2201                         mul_v2_fl(dir_vec, lambda);
2202
2203                         copy_v2_v2(pixel, tface[target_face].uv[target_uv1]);
2204                         add_v2_v2(pixel, dir_vec);
2205                         pixel[0] = (pixel[0] * (float)w) - 0.5f;
2206                         pixel[1] = (pixel[1] * (float)h) - 0.5f;
2207
2208                         final_pixel[0] = (int)floor(pixel[0]);
2209                         final_pixel[1] = (int)floor(pixel[1]);
2210
2211                         /* If current pixel uv is outside of texture    */
2212                         if (final_pixel[0] < 0 || final_pixel[0] >= w) return OUT_OF_TEXTURE;
2213                         if (final_pixel[1] < 0 || final_pixel[1] >= h) return OUT_OF_TEXTURE;
2214
2215                         final_index = final_pixel[0] + w * final_pixel[1];
2216
2217                         /* If we ended up to our origin point ( mesh has smaller than pixel sized faces)        */
2218                         if (final_index == (px + w * py)) return NOT_FOUND;
2219                         /* If found pixel still lies on wrong face ( mesh has smaller than pixel sized faces)   */
2220                         if (tempPoints[final_index].face_index != target_face) return NOT_FOUND;
2221
2222                         /*
2223                          *      If final point is an "edge pixel", use it's "real" neighbor instead
2224                          */
2225                         if (tempPoints[final_index].neighbour_pixel != -1) final_index = cPoint->neighbour_pixel;
2226
2227                         return final_index;
2228                 }
2229         }
2230 }
2231
2232 /*
2233  *      Create a surface for uv image sequence format
2234  */
2235 int dynamicPaint_createUVSurface(Scene *scene, DynamicPaintSurface *surface)
2236 {
2237         /* Antialias jitter point relative coords       */
2238         float jitter5sample[10] =  {0.0f, 0.0f,
2239                                         -0.2f, -0.4f,
2240                                         0.2f, 0.4f,
2241                                         0.4f, -0.2f,
2242                                         -0.4f, 0.3f};
2243         int ty;
2244         int w, h;
2245         int numOfFaces;
2246         char uvname[MAX_CUSTOMDATA_LAYER_NAME];
2247         int active_points = 0;
2248         int error = 0;
2249
2250         PaintSurfaceData *sData;
2251         DynamicPaintCanvasSettings *canvas = surface->canvas;
2252         DerivedMesh *dm = canvas->dm;
2253
2254         PaintUVPoint *tempPoints = NULL;
2255         Vec3f *tempWeights = NULL;
2256         MFace *mface = NULL;
2257         MTFace *tface = NULL;
2258         Bounds2D *faceBB = NULL;
2259         int *final_index;
2260         int aa_samples;
2261
2262         if (!dm)
2263                 return setError(canvas, N_("Canvas mesh not updated"));
2264         if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ)
2265                 return setError(canvas, N_("Cannot bake non-'image sequence' formats"));
2266
2267         numOfFaces = dm->getNumTessFaces(dm);
2268         mface = dm->getTessFaceArray(dm);
2269
2270         /* get uv map */
2271         CustomData_validate_layer_name(&dm->faceData, CD_MTFACE, surface->uvlayer_name, uvname);
2272         tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname);
2273
2274         /* Check for validity   */
2275         if (!tface)
2276                 return setError(canvas, N_("No UV data on canvas"));
2277         if (surface->image_resolution < 16 || surface->image_resolution > 8192)
2278                 return setError(canvas, N_("Invalid resolution"));
2279
2280         w = h = surface->image_resolution;
2281
2282         /*
2283          *      Start generating the surface
2284          */
2285         printf("DynamicPaint: Preparing UV surface of %ix%i pixels and %i faces.\n", w, h, numOfFaces);
2286
2287         /* Init data struct */
2288         if (surface->data) dynamicPaint_freeSurfaceData(surface);
2289         sData = surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData");
2290         if (!surface->data)
2291                 return setError(canvas, N_("Not enough free memory"));
2292
2293         aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2294         tempPoints = (struct PaintUVPoint *) MEM_callocN(w * h * sizeof(struct PaintUVPoint), "Temp PaintUVPoint");
2295         if (!tempPoints) error = 1;
2296
2297         final_index = (int *) MEM_callocN(w * h * sizeof(int), "Temp UV Final Indexes");
2298         if (!final_index) error = 1;
2299
2300         tempWeights = (struct Vec3f *) MEM_mallocN(w * h * aa_samples * sizeof(struct Vec3f), "Temp bWeights");
2301         if (!tempWeights) error = 1;
2302
2303         /*
2304          *      Generate a temporary bounding box array for UV faces to optimize
2305          *      the pixel-inside-a-face search.
2306          */
2307         if (!error) {
2308                 faceBB = (struct Bounds2D *) MEM_mallocN(numOfFaces * sizeof(struct Bounds2D), "MPCanvasFaceBB");
2309                 if (!faceBB) error = 1;
2310         }
2311
2312         if (!error)
2313                 for (ty = 0; ty < numOfFaces; ty++) {
2314                         int numOfVert = (mface[ty].v4) ? 4 : 3;
2315                         int i;
2316
2317                         copy_v2_v2(faceBB[ty].min, tface[ty].uv[0]);
2318                         copy_v2_v2(faceBB[ty].max, tface[ty].uv[0]);
2319
2320                         for (i = 1; i < numOfVert; i++) {
2321                                 if (tface[ty].uv[i][0] < faceBB[ty].min[0]) faceBB[ty].min[0] = tface[ty].uv[i][0];
2322                                 if (tface[ty].uv[i][1] < faceBB[ty].min[1]) faceBB[ty].min[1] = tface[ty].uv[i][1];
2323                                 if (tface[ty].uv[i][0] > faceBB[ty].max[0]) faceBB[ty].max[0] = tface[ty].uv[i][0];
2324                                 if (tface[ty].uv[i][1] > faceBB[ty].max[1]) faceBB[ty].max[1] = tface[ty].uv[i][1];
2325
2326                         }
2327                 }
2328
2329         /*
2330          *      Loop through every pixel and check
2331          *      if pixel is uv-mapped on a canvas face.
2332          */
2333         if (!error) {
2334 #pragma omp parallel for schedule(static)
2335                 for (ty = 0; ty < h; ty++) {
2336                         int tx;
2337                         for (tx = 0; tx < w; tx++) {
2338                                 int i, sample;
2339                                 int index = tx + w * ty;
2340                                 PaintUVPoint *tPoint = (&tempPoints[index]);
2341
2342                                 short isInside = 0; /* if point is inside a uv face */
2343
2344                                 float d1[2], d2[2], d3[2], point[5][2];
2345                                 float dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
2346
2347                                 /* Init per pixel settings */
2348                                 tPoint->face_index = -1;
2349                                 tPoint->neighbour_pixel = -1;
2350                                 tPoint->pixel_index = index;
2351
2352                                 /* Actual pixel center, used when collision is found    */
2353                                 point[0][0] = ((float)tx + 0.5f) / w;
2354                                 point[0][1] = ((float)ty + 0.5f) / h;
2355
2356                                 /*
2357                                  * A pixel middle sample isn't enough to find very narrow polygons
2358                                  * So using 4 samples of each corner too
2359                                  */
2360                                 point[1][0] = ((float)tx) / w;
2361                                 point[1][1] = ((float)ty) / h;
2362
2363                                 point[2][0] = ((float)tx + 1) / w;
2364                                 point[2][1] = ((float)ty) / h;
2365
2366                                 point[3][0] = ((float)tx) / w;
2367                                 point[3][1] = ((float)ty + 1) / h;
2368
2369                                 point[4][0] = ((float)tx + 1) / w;
2370                                 point[4][1] = ((float)ty + 1) / h;
2371
2372
2373                                 /* Loop through samples, starting from middle point     */
2374                                 for (sample = 0; sample < 5; sample++) {
2375                                         
2376                                         /* Loop through every face in the mesh  */
2377                                         for (i = 0; i < numOfFaces; i++) {
2378
2379                                                 /* Check uv bb  */
2380                                                 if (faceBB[i].min[0] > (point[sample][0])) continue;
2381                                                 if (faceBB[i].min[1] > (point[sample][1])) continue;
2382                                                 if (faceBB[i].max[0] < (point[sample][0])) continue;
2383                                                 if (faceBB[i].max[1] < (point[sample][1])) continue;
2384
2385                                                 /*  Calculate point inside a triangle check
2386                                                  *      for uv0, 1, 2 */
2387                                                 sub_v2_v2v2(d1,  tface[i].uv[2], tface[i].uv[0]);   // uv2 - uv0
2388                                                 sub_v2_v2v2(d2,  tface[i].uv[1], tface[i].uv[0]);   // uv1 - uv0
2389                                                 sub_v2_v2v2(d3,  point[sample], tface[i].uv[0]);    // point - uv0
2390
2391                                                 dot00 = d1[0] * d1[0] + d1[1] * d1[1];
2392                                                 dot01 = d1[0] * d2[0] + d1[1] * d2[1];
2393                                                 dot02 = d1[0] * d3[0] + d1[1] * d3[1];
2394                                                 dot11 = d2[0] * d2[0] + d2[1] * d2[1];
2395                                                 dot12 = d2[0] * d3[0] + d2[1] * d3[1];
2396
2397                                                 invDenom = (dot00 * dot11 - dot01 * dot01);
2398                                                 invDenom = invDenom ? 1.0f / invDenom : 1.0f;
2399                                                 u = (dot11 * dot02 - dot01 * dot12) * invDenom;
2400                                                 v = (dot00 * dot12 - dot01 * dot02) * invDenom;
2401
2402                                                 if ((u > 0) && (v > 0) && (u + v < 1)) { isInside = 1; } /* is inside a triangle */
2403
2404                                                 /*  If collision wasn't found but the face is a quad
2405                                                  *      do another check for the second half */
2406                                                 if ((!isInside) && mface[i].v4) {
2407
2408                                                         /* change d2 to test the other half     */
2409                                                         sub_v2_v2v2(d2,  tface[i].uv[3], tface[i].uv[0]);   // uv3 - uv0
2410
2411                                                         /* test again   */
2412                                                         dot00 = d1[0] * d1[0] + d1[1] * d1[1];
2413                                                         dot01 = d1[0] * d2[0] + d1[1] * d2[1];
2414                                                         dot02 = d1[0] * d3[0] + d1[1] * d3[1];
2415                                                         dot11 = d2[0] * d2[0] + d2[1] * d2[1];
2416                                                         dot12 = d2[0] * d3[0] + d2[1] * d3[1];
2417
2418                                                         invDenom = (dot00 * dot11 - dot01 * dot01);
2419                                                         invDenom = invDenom ? 1.0f / invDenom : 1.0f;
2420                                                         u = (dot11 * dot02 - dot01 * dot12) * invDenom;
2421                                                         v = (dot00 * dot12 - dot01 * dot02) * invDenom;
2422
2423                                                         if ((u > 0) && (v > 0) && (u + v < 1)) { isInside = 2; } /* is inside the second half of the quad */
2424
2425                                                 }
2426
2427                                                 /*
2428                                                  *      If point was inside the face
2429                                                  */
2430                                                 if (isInside != 0) {
2431
2432                                                         float uv1co[2], uv2co[2], uv3co[2], uv[2];
2433                                                         int j;
2434
2435                                                         /* Get triagnle uvs     */
2436                                                         if (isInside == 1) {
2437                                                                 copy_v2_v2(uv1co, tface[i].uv[0]);
2438                                                                 copy_v2_v2(uv2co, tface[i].uv[1]);
2439                                                                 copy_v2_v2(uv3co, tface[i].uv[2]);
2440                                                         }
2441                                                         else {
2442                                                                 copy_v2_v2(uv1co, tface[i].uv[0]);
2443                                                                 copy_v2_v2(uv2co, tface[i].uv[2]);
2444                                                                 copy_v2_v2(uv3co, tface[i].uv[3]);
2445                                                         }
2446
2447                                                         /* Add b-weights per anti-aliasing sample       */
2448                                                         for (j = 0; j < aa_samples; j++) {
2449                                                                 uv[0] = point[0][0] + jitter5sample[j * 2] / w;
2450                                                                 uv[1] = point[0][1] + jitter5sample[j * 2 + 1] / h;
2451
2452                                                                 barycentric_weights_v2(uv1co, uv2co, uv3co, uv, tempWeights[index * aa_samples + j].v);
2453                                                         }
2454
2455                                                         /* Set surface point face values        */
2456                                                         tPoint->face_index = i;                         /* face index */
2457                                                         tPoint->quad = (isInside == 2) ? 1 : 0;     /* quad or tri part*/
2458
2459                                                         /* save vertex indexes  */
2460                                                         tPoint->v1 = mface[i].v1;
2461                                                         tPoint->v2 = (isInside == 2) ? mface[i].v3 : mface[i].v2;
2462                                                         tPoint->v3 = (isInside == 2) ? mface[i].v4 : mface[i].v3;
2463
2464                                                         sample = 5; /* make sure we exit sample loop as well */
2465                                                         break;
2466                                                 }
2467                                         }
2468                                 } /* sample loop */
2469                         }
2470                 }
2471
2472                 /*
2473                  *      Now loop through every pixel that was left without index
2474                  *      and find if they have neighboring pixels that have an index.
2475                  *      If so use that polygon as pixel surface.
2476                  *      (To avoid seams on uv island edges)
2477                  */
2478 #pragma omp parallel for schedule(static)
2479                 for (ty = 0; ty < h; ty++) {
2480                         int tx;
2481                         for (tx = 0; tx < w; tx++) {
2482                                 int index = tx + w * ty;
2483                                 PaintUVPoint *tPoint = (&tempPoints[index]);
2484
2485                                 /* If point isn't't on canvas mesh      */
2486                                 if (tPoint->face_index == -1) {
2487                                         int u_min, u_max, v_min, v_max;
2488                                         int u, v, ind;
2489                                         float point[2];
2490
2491                                         /* get loop area        */
2492                                         u_min = (tx > 0) ? -1 : 0;
2493                                         u_max = (tx < (w - 1)) ? 1 : 0;
2494                                         v_min = (ty > 0) ? -1 : 0;
2495                                         v_max = (ty < (h - 1)) ? 1 : 0;
2496
2497                                         point[0] = ((float)tx + 0.5f) / w;
2498                                         point[1] = ((float)ty + 0.5f) / h;
2499
2500                                         /* search through defined area for neighbor     */
2501                                         for (u = u_min; u <= u_max; u++)
2502                                                 for (v = v_min; v <= v_max; v++) {
2503                                                         /* if not this pixel itself     */
2504                                                         if (u != 0 || v != 0) {
2505                                                                 ind = (tx + u) + w * (ty + v);
2506
2507                                                                 /* if neighbor has index        */
2508                                                                 if (tempPoints[ind].face_index != -1) {
2509
2510                                                                         float uv1co[2], uv2co[2], uv3co[2], uv[2];
2511                                                                         int i = tempPoints[ind].face_index, j;
2512
2513                                                                         /* Now calculate pixel data for this pixel as it was on polygon surface */
2514                                                                         if (!tempPoints[ind].quad) {
2515                                                                                 copy_v2_v2(uv1co, tface[i].uv[0]);
2516                                                                                 copy_v2_v2(uv2co, tface[i].uv[1]);
2517                                                                                 copy_v2_v2(uv3co, tface[i].uv[2]);
2518                                                                         }
2519                                                                         else {
2520                                                                                 copy_v2_v2(uv1co, tface[i].uv[0]);
2521                                                                                 copy_v2_v2(uv2co, tface[i].uv[2]);
2522                                                                                 copy_v2_v2(uv3co, tface[i].uv[3]);
2523                                                                         }
2524
2525                                                                         /* Add b-weights per anti-aliasing sample       */
2526                                                                         for (j = 0; j < aa_samples; j++) {
2527
2528                                                                                 uv[0] = point[0] + jitter5sample[j * 2] / w;
2529                                                                                 uv[1] = point[1] + jitter5sample[j * 2 + 1] / h;
2530                                                                                 barycentric_weights_v2(uv1co, uv2co, uv3co, uv, tempWeights[index * aa_samples + j].v);
2531                                                                         }
2532
2533                                                                         /* Set values   */
2534                                                                         tPoint->neighbour_pixel = ind;              // face index
2535                                                                         tPoint->quad = tempPoints[ind].quad;        // quad or tri
2536
2537                                                                         /* save vertex indexes  */
2538                                                                         tPoint->v1 = mface[i].v1;
2539                                                                         tPoint->v2 = (tPoint->quad) ? mface[i].v3 : mface[i].v2;
2540                                                                         tPoint->v3 = (tPoint->quad) ? mface[i].v4 : mface[i].v3;
2541
2542                                                                         u = u_max + 1;  /* make sure we exit outer loop as well */
2543                                                                         break;
2544                                                                 }
2545                                                         }
2546                                                 }
2547                                 }
2548                         }
2549                 }
2550
2551                 /*
2552                  *      When base loop is over convert found neighbor indexes to real ones
2553                  *      Also count the final number of active surface points
2554                  */
2555                 for (ty = 0; ty < h; ty++) {
2556                         int tx;
2557                         for (tx = 0; tx < w; tx++) {
2558                                 int index = tx + w * ty;
2559                                 PaintUVPoint *tPoint = (&tempPoints[index]);
2560
2561                                 if (tPoint->face_index == -1 && tPoint->neighbour_pixel != -1) tPoint->face_index = tempPoints[tPoint->neighbour_pixel].face_index;
2562                                 if (tPoint->face_index != -1) active_points++;
2563                         }
2564                 }
2565
2566                 /*      Generate surface adjacency data. */
2567                 {
2568                         int i, cursor = 0;
2569
2570                         /* Create a temporary array of final indexes (before unassigned
2571                          *  pixels have been dropped) */
2572                         for (i = 0; i < w * h; i++) {
2573                                 if (tempPoints[i].face_index != -1) {
2574                                         final_index[i] = cursor;
2575                                         cursor++;
2576                                 }
2577                         }
2578                         /* allocate memory */
2579                         sData->total_points = w * h;
2580                         dynamicPaint_initAdjacencyData(surface, 1);
2581
2582                         if (sData->adj_data) {
2583                                 PaintAdjData *ed = sData->adj_data;
2584                                 unsigned int n_pos = 0;
2585                                 for (ty = 0; ty < h; ty++) {
2586                                         int tx;
2587                                         for (tx = 0; tx < w; tx++) {
2588                                                 int i, index = tx + w * ty;
2589
2590                                                 if (tempPoints[index].face_index != -1) {
2591                                                         ed->n_index[final_index[index]] = n_pos;
2592                                                         ed->n_num[final_index[index]] = 0;
2593
2594                                                         for (i = 0; i < 8; i++) {
2595
2596                                                                 /* Try to find a neighboring pixel in defined direction
2597                                                                  *  If not found, -1 is returned */
2598                                                                 int n_target = dynamicPaint_findNeighbourPixel(tempPoints, dm, uvname, w, h, tx, ty, i);
2599
2600                                                                 if (n_target >= 0) {
2601                                                                         ed->n_target[n_pos] = final_index[n_target];
2602                                                                         ed->n_num[final_index[index]]++;
2603                                                                         n_pos++;
2604                                                                 }
2605                                                                 else if (n_target == ON_MESH_EDGE || n_target == OUT_OF_TEXTURE) {
2606                                                                         ed->flags[final_index[index]] |= ADJ_ON_MESH_EDGE;
2607                                                                 }
2608                                                         }
2609                                                 }
2610                                         }
2611                                 }
2612                         }
2613                 }
2614
2615                 /* Create final surface data without inactive points */
2616                 {
2617                         ImgSeqFormatData *f_data = MEM_callocN(sizeof(struct ImgSeqFormatData), "ImgSeqFormatData");
2618                         if (f_data) {
2619                                 f_data->uv_p = MEM_callocN(active_points * sizeof(struct PaintUVPoint), "PaintUVPoint");
2620                                 f_data->barycentricWeights = MEM_callocN(active_points * aa_samples * sizeof(struct Vec3f), "PaintUVPoint");
2621
2622                                 if (!f_data->uv_p || !f_data->barycentricWeights) error = 1;
2623                         }
2624                         else {
2625                                 error = 1;
2626                         }
2627
2628                         sData->total_points = active_points;
2629                         
2630                         /* in case of allocation error, free everything */
2631                         if (error) {
2632                                 if (f_data) {
2633                                         if (f_data->uv_p) MEM_freeN(f_data->uv_p);
2634                                         if (f_data->barycentricWeights) MEM_freeN(f_data->barycentricWeights);
2635                                         MEM_freeN(f_data);
2636                                 }
2637                         }
2638                         else {
2639                                 int index, cursor = 0;
2640                                 sData->total_points = active_points;
2641                                 sData->format_data = f_data;
2642
2643                                 for (index = 0; index < (w * h); index++) {
2644                                         if (tempPoints[index].face_index != -1) {
2645                                                 memcpy(&f_data->uv_p[cursor], &tempPoints[index], sizeof(PaintUVPoint));
2646                                                 memcpy(&f_data->barycentricWeights[cursor * aa_samples], &tempWeights[index * aa_samples], sizeof(Vec3f) * aa_samples);
2647                                                 cursor++;
2648                                         }
2649                                 }
2650                         }
2651                 }
2652         }
2653         if (error == 1)
2654                 setError(canvas, N_("Not enough free memory"));
2655
2656         if (faceBB) MEM_freeN(faceBB);
2657         if (tempPoints) MEM_freeN(tempPoints);
2658         if (tempWeights) MEM_freeN(tempWeights);
2659         if (final_index) MEM_freeN(final_index);
2660
2661         /* Init surface type data */
2662         if (!error) {
2663                 dynamicPaint_allocateSurfaceType(surface);
2664
2665 #if 0
2666                 /*  -----------------------------------------------------------------
2667                  *      For debug, output pixel statuses to the color map
2668                  *      -----------------------------------------------------------------*/
2669 #pragma omp parallel for schedule(static)
2670                 for (index = 0; index < sData->total_points; index++)
2671                 {
2672                         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
2673                         PaintUVPoint *uvPoint = &((PaintUVPoint *)f_data->uv_p)[index];
2674                         PaintPoint *pPoint = &((PaintPoint *)sData->type_data)[index];
2675                         pPoint->alpha = 1.0f;
2676
2677                         /* Every pixel that is assigned as "edge pixel" gets blue color */
2678                         if (uvPoint->neighbour_pixel != -1) pPoint->color[2] = 1.0f;
2679                         /* and every pixel that finally got an polygon gets red color   */
2680                         if (uvPoint->face_index != -1) pPoint->color[0] = 1.0f;
2681                         /* green color shows pixel face index hash      */
2682                         if (uvPoint->face_index != -1) pPoint->color[1] = (float)(uvPoint->face_index % 255) / 256.0f;
2683                 }
2684
2685 #endif
2686                 dynamicPaint_setInitialColor(scene, surface);
2687         }
2688
2689         return (error == 0);
2690 }
2691
2692 /*
2693  *      Outputs an image file from uv surface data.
2694  */
2695 void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filename, short output_layer)
2696 {
2697         int index;
2698         ImBuf *ibuf = NULL;
2699         PaintSurfaceData *sData = surface->data;
2700         ImgSeqFormatData *f_data = (ImgSeqFormatData *)sData->format_data;
2701         /* OpenEXR or PNG       */
2702         int format = (surface->image_fileformat & MOD_DPAINT_IMGFORMAT_OPENEXR) ? R_IMF_IMTYPE_OPENEXR : R_IMF_IMTYPE_PNG;
2703         char output_file[FILE_MAX];
2704
2705         if (!sData->type_data) {
2706                 setError(surface->canvas, N_("Image save failed: invalid surface"));
2707                 return;
2708         }
2709         /* if selected format is openexr, but current build doesnt support one */
2710 #ifndef WITH_OPENEXR
2711         if (format == R_IMF_IMTYPE_OPENEXR) format = R_IMF_IMTYPE_PNG;
2712 #endif
2713         BLI_strncpy(output_file, filename, sizeof(output_file));
2714         BKE_add_image_extension_from_type(output_file, format);
2715
2716         /* Validate output file path    */
2717         BLI_path_abs(output_file, G.main->name);
2718         BLI_make_existing_file(output_file);
2719
2720         /* Init image buffer    */
2721         ibuf = IMB_allocImBuf(surface->image_resolution, surface->image_resolution, 32, IB_rectfloat);
2722         if (ibuf == NULL) {
2723                 setError(surface->canvas, N_("Image save failed: not enough free memory"));
2724                 return;
2725         }
2726
2727 #pragma omp parallel for schedule(static)
2728         for (index = 0; index < sData->total_points; index++) {
2729                 int pos = f_data->uv_p[index].pixel_index * 4;  /* image buffer position */
2730
2731                 /* Set values of preferred type */
2732                 if (output_layer == 1) {
2733                         /* wetmap */
2734                         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
2735                                 PaintPoint *point = &((PaintPoint *)sData->type_data)[index];
2736                                 float value = (point->wetness > 1.0f) ? 1.0f : point->wetness;
2737
2738                                 ibuf->rect_float[pos] = value;
2739                                 ibuf->rect_float[pos + 1] = value;
2740                                 ibuf->rect_float[pos + 2] = value;
2741                                 ibuf->rect_float[pos + 3] = 1.0f;
2742                         }
2743                 }
2744                 else if (output_layer == 0) {
2745                         /* Paintmap */
2746                         if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
2747                                 PaintPoint *point = &((PaintPoint *)sData->type_data)[index];
2748
2749                                 /* blend wet and dry layers */
2750                                 blendColors(point->color, point->alpha, point->e_color, point->e_alpha, &ibuf->rect_float[pos]);
2751
2752                                 /* Multiply color by alpha if enabled   */
2753                                 if (surface->flags & MOD_DPAINT_MULALPHA) {
2754                                         ibuf->rect_float[pos]   *= ibuf->rect_float[pos + 3];
2755                                         ibuf->rect_float[pos + 1] *= ibuf->rect_float[pos + 3];
2756                                         ibuf->rect_float[pos + 2] *= ibuf->rect_float[pos + 3];
2757                                 }
2758                         }
2759                         /* displace */
2760                         else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
2761                                 float depth = ((float *)sData->type_data)[index];
2762                                 if (surface->depth_clamp)
2763                                         depth /= surface->depth_clamp;
2764
2765                                 if (surface->disp_type == MOD_DPAINT_DISP_DISPLACE) {
2766                                         depth = (0.5f - depth / 2.0f);
2767                                 }
2768
2769                                 CLAMP(depth, 0.0f, 1.0f);
2770
2771                                 ibuf->rect_float[pos] = depth;
2772                                 ibuf->rect_float[pos + 1] = depth;
2773                                 ibuf->rect_float[pos + 2] = depth;
2774                                 ibuf->rect_float[pos + 3] = 1.0f;
2775                         }
2776                         /* waves */
2777                         else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
2778                                 PaintWavePoint *wPoint = &((PaintWavePoint *)sData->type_data)[index];
2779                                 float depth = wPoint->height;
2780                                 if (surface->depth_clamp)
2781                                         depth /= surface->depth_clamp;
2782                                 depth = (0.5f + depth / 2.0f);
2783                                 CLAMP(depth, 0.0f, 1.0f);
2784
2785                                 ibuf->rect_float[pos] = depth;
2786                                 ibuf->rect_float[pos + 1] = depth;
2787                                 ibuf->rect_float[pos + 2] = depth;
2788                                 ibuf->rect_float[pos + 3] = 1.0f;
2789                         }
2790                 }
2791         }
2792
2793         /* Set output format, png in case exr isn't supported */
2794         ibuf->ftype = PNG | 95;
2795 #ifdef WITH_OPENEXR