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