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