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