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