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