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