Merging r48981 through r48984 from trunk into soc-2011-tomato
[blender.git] / source / blender / blenkernel / intern / mask.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2012 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation,
22  *                 Sergey Sharybin
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/mask.c
28  *  \ingroup bke
29  */
30
31 #include <stddef.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_utildefines.h"
37 #include "BLI_path_util.h"
38 #include "BLI_string.h"
39 #include "BLI_listbase.h"
40 #include "BLI_math.h"
41
42 #include "DNA_mask_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_movieclip_types.h"
48 #include "DNA_tracking_types.h"
49
50 #include "BKE_curve.h"
51 #include "BKE_global.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_mask.h"
55 #include "BKE_tracking.h"
56 #include "BKE_movieclip.h"
57 #include "BKE_utildefines.h"
58
59 #include "raskter.h"
60
61 #ifdef USE_MANGO_MASK_CACHE_HACK
62
63 #include "BLI_threads.h"
64
65 typedef struct MaskRasterCache {
66         float *buffer;
67         int width, height;
68         short do_aspect_correct;
69         short do_mask_aa;
70         short do_feather;
71
72         ListBase layers;
73 } MaskRasterCache;
74 #endif
75
76 static MaskSplinePoint *mask_spline_point_next(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
77 {
78         if (point == &points_array[spline->tot_point - 1]) {
79                 if (spline->flag & MASK_SPLINE_CYCLIC) {
80                         return &points_array[0];
81                 }
82                 else {
83                         return NULL;
84                 }
85         }
86         else {
87                 return point + 1;
88         }
89 }
90
91 static MaskSplinePoint *mask_spline_point_prev(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
92 {
93         if (point == points_array) {
94                 if (spline->flag & MASK_SPLINE_CYCLIC) {
95                         return &points_array[spline->tot_point - 1];
96                 }
97                 else {
98                         return NULL;
99                 }
100         }
101         else {
102                 return point - 1;
103         }
104 }
105
106 static BezTriple *mask_spline_point_next_bezt(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
107 {
108         if (point == &points_array[spline->tot_point - 1]) {
109                 if (spline->flag & MASK_SPLINE_CYCLIC) {
110                         return &(points_array[0].bezt);
111                 }
112                 else {
113                         return NULL;
114                 }
115         }
116         else {
117                 return &((point + 1))->bezt;
118         }
119 }
120
121 #if 0
122 static BezTriple *mask_spline_point_prev_bezt(MaskSpline *spline, MaskSplinePoint *points_array, MaskSplinePoint *point)
123 {
124         if (point == points_array) {
125                 if (spline->flag & MASK_SPLINE_CYCLIC) {
126                         return &(points_array[0].bezt);
127                 }
128                 else  {
129                         return NULL;
130                 }
131         }
132         else {
133                 return &((point - 1))->bezt;
134         }
135 }
136 #endif
137
138 MaskSplinePoint *BKE_mask_spline_point_array(MaskSpline *spline)
139 {
140         return spline->points_deform ? spline->points_deform : spline->points;
141 }
142
143 MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, MaskSplinePoint *point_ref)
144 {
145         if ((point_ref >= spline->points) && (point_ref < &spline->points[spline->tot_point])) {
146                 return spline->points;
147         }
148
149         if ((point_ref >= spline->points_deform) && (point_ref < &spline->points_deform[spline->tot_point])) {
150                 return spline->points_deform;
151         }
152
153         BLI_assert(!"wrong array");
154         return NULL;
155 }
156
157 /* mask layers */
158
159 MaskLayer *BKE_mask_layer_new(Mask *mask, const char *name)
160 {
161         MaskLayer *masklay = MEM_callocN(sizeof(MaskLayer), __func__);
162
163         if (name && name[0])
164                 BLI_strncpy(masklay->name, name, sizeof(masklay->name));
165         else
166                 strcpy(masklay->name, "MaskLayer");
167
168         BLI_addtail(&mask->masklayers, masklay);
169
170         BKE_mask_layer_unique_name(mask, masklay);
171
172         mask->masklay_tot++;
173
174         masklay->alpha = 1.0f;
175
176         return masklay;
177 }
178
179 /* note: may still be hidden, caller needs to check */
180 MaskLayer *BKE_mask_layer_active(Mask *mask)
181 {
182         return BLI_findlink(&mask->masklayers, mask->masklay_act);
183 }
184
185 void BKE_mask_layer_active_set(Mask *mask, MaskLayer *masklay)
186 {
187         mask->masklay_act = BLI_findindex(&mask->masklayers, masklay);
188 }
189
190 void BKE_mask_layer_remove(Mask *mask, MaskLayer *masklay)
191 {
192         BLI_remlink(&mask->masklayers, masklay);
193         BKE_mask_layer_free(masklay);
194
195         mask->masklay_tot--;
196
197         if (mask->masklay_act >= mask->masklay_tot)
198                 mask->masklay_act = mask->masklay_tot - 1;
199 }
200
201 void BKE_mask_layer_unique_name(Mask *mask, MaskLayer *masklay)
202 {
203         BLI_uniquename(&mask->masklayers, masklay, "MaskLayer", '.', offsetof(MaskLayer, name), sizeof(masklay->name));
204 }
205
206 MaskLayer *BKE_mask_layer_copy(MaskLayer *layer)
207 {
208         MaskLayer *layer_new;
209         MaskSpline *spline;
210
211         layer_new = MEM_callocN(sizeof(MaskLayer), "new mask layer");
212
213         BLI_strncpy(layer_new->name, layer->name, sizeof(layer_new->name));
214
215         layer_new->alpha = layer->alpha;
216         layer_new->blend = layer->blend;
217         layer_new->blend_flag = layer->blend_flag;
218         layer_new->flag = layer->flag;
219         layer_new->restrictflag = layer->restrictflag;
220
221         for (spline = layer->splines.first; spline; spline = spline->next) {
222                 MaskSpline *spline_new = BKE_mask_spline_copy(spline);
223
224                 BLI_addtail(&layer_new->splines, spline_new);
225         }
226
227         return layer_new;
228 }
229
230 void BKE_mask_layer_copy_list(ListBase *masklayers_new, ListBase *masklayers)
231 {
232         MaskLayer *layer;
233
234         for (layer = masklayers->first; layer; layer = layer->next) {
235                 MaskLayer *layer_new = BKE_mask_layer_copy(layer);
236
237                 BLI_addtail(masklayers_new, layer_new);
238         }
239 }
240
241 /* splines */
242
243 MaskSpline *BKE_mask_spline_add(MaskLayer *masklay)
244 {
245         MaskSpline *spline;
246
247         spline = MEM_callocN(sizeof(MaskSpline), "new mask spline");
248         BLI_addtail(&masklay->splines, spline);
249
250         /* spline shall have one point at least */
251         spline->points = MEM_callocN(sizeof(MaskSplinePoint), "new mask spline point");
252         spline->tot_point = 1;
253
254         /* cyclic shapes are more usually used */
255         // spline->flag |= MASK_SPLINE_CYCLIC; // disable because its not so nice for drawing. could be done differently
256
257         spline->weight_interp = MASK_SPLINE_INTERP_EASE;
258
259         BKE_mask_parent_init(&spline->parent);
260
261         return spline;
262 }
263
264 int BKE_mask_spline_resolution(MaskSpline *spline, int width, int height)
265 {
266         float max_segment = 0.01f;
267         int i, resol = 1;
268
269         if (width != 0 && height != 0) {
270                 if (width >= height)
271                         max_segment = 1.0f / (float) width;
272                 else
273                         max_segment = 1.0f / (float) height;
274         }
275
276         for (i = 0; i < spline->tot_point; i++) {
277                 MaskSplinePoint *point = &spline->points[i];
278                 BezTriple *bezt, *bezt_next;
279                 float a, b, c, len;
280                 int cur_resol;
281
282                 bezt = &point->bezt;
283                 bezt_next = mask_spline_point_next_bezt(spline, spline->points, point);
284
285                 if (bezt_next == NULL) {
286                         break;
287                 }
288
289                 a = len_v3v3(bezt->vec[1], bezt->vec[2]);
290                 b = len_v3v3(bezt->vec[2], bezt_next->vec[0]);
291                 c = len_v3v3(bezt_next->vec[0], bezt_next->vec[1]);
292
293                 len = a + b + c;
294                 cur_resol = len / max_segment;
295
296                 resol = MAX2(resol, cur_resol);
297         }
298
299         return resol;
300 }
301
302 int BKE_mask_spline_feather_resolution(MaskSpline *spline, int width, int height)
303 {
304         const float max_segment = 0.005;
305         int resol = BKE_mask_spline_resolution(spline, width, height);
306         float max_jump = 0.0f;
307         int i;
308
309         for (i = 0; i < spline->tot_point; i++) {
310                 MaskSplinePoint *point = &spline->points[i];
311                 float prev_u, prev_w;
312                 int j;
313
314                 prev_u = 0.0f;
315                 prev_w = point->bezt.weight;
316
317                 for (j = 0; j < point->tot_uw; j++) {
318                         float jump = fabsf((point->uw[j].w - prev_w) / (point->uw[j].u - prev_u));
319
320                         max_jump = MAX2(max_jump, jump);
321
322                         prev_u = point->uw[j].u;
323                         prev_w = point->uw[j].w;
324                 }
325         }
326
327         resol += max_jump / max_segment;
328
329         return resol;
330 }
331
332 int BKE_mask_spline_differentiate_calc_total(const MaskSpline *spline, const int resol)
333 {
334         int len;
335
336         /* count */
337         len = (spline->tot_point - 1) * resol;
338
339         if (spline->flag & MASK_SPLINE_CYCLIC) {
340                 len += resol;
341         }
342         else {
343                 len++;
344         }
345
346         return len;
347 }
348
349 float (*BKE_mask_spline_differentiate_with_resolution_ex(MaskSpline *spline, const int resol,
350                                                          int *tot_diff_point))[2]
351 {
352         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
353
354         MaskSplinePoint *point, *prev;
355         float (*diff_points)[2], (*fp)[2];
356         const int tot = BKE_mask_spline_differentiate_calc_total(spline, resol);
357         int a;
358
359         if (spline->tot_point <= 1) {
360                 /* nothing to differentiate */
361                 *tot_diff_point = 0;
362                 return NULL;
363         }
364
365         /* len+1 because of 'forward_diff_bezier' function */
366         *tot_diff_point = tot;
367         diff_points = fp = MEM_mallocN((tot + 1) * sizeof(*diff_points), "mask spline vets");
368
369         a = spline->tot_point - 1;
370         if (spline->flag & MASK_SPLINE_CYCLIC)
371                 a++;
372
373         prev = points_array;
374         point = prev + 1;
375
376         while (a--) {
377                 BezTriple *prevbezt;
378                 BezTriple *bezt;
379                 int j;
380
381                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC))
382                         point = points_array;
383
384                 prevbezt = &prev->bezt;
385                 bezt = &point->bezt;
386
387                 for (j = 0; j < 2; j++) {
388                         BKE_curve_forward_diff_bezier(prevbezt->vec[1][j], prevbezt->vec[2][j],
389                                                       bezt->vec[0][j], bezt->vec[1][j],
390                                                       &(*fp)[j], resol, 2 * sizeof(float));
391                 }
392
393                 fp += resol;
394
395                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC) == 0) {
396                         copy_v2_v2(*fp, bezt->vec[1]);
397                 }
398
399                 prev = point;
400                 point++;
401         }
402
403         return diff_points;
404 }
405
406 float (*BKE_mask_spline_differentiate_with_resolution(MaskSpline *spline, int width, int height,
407                                                       int *tot_diff_point))[2]
408 {
409         int resol = BKE_mask_spline_resolution(spline, width, height);
410
411         return BKE_mask_spline_differentiate_with_resolution_ex(spline, resol, tot_diff_point);
412 }
413
414 float (*BKE_mask_spline_differentiate(MaskSpline *spline, int *tot_diff_point))[2]
415 {
416         return BKE_mask_spline_differentiate_with_resolution(spline, 0, 0, tot_diff_point);
417 }
418
419 /* ** feather points self-intersection collapse routine ** */
420
421 typedef struct FeatherEdgesBucket {
422         int tot_segment;
423         int (*segments)[2];
424         int alloc_segment;
425 } FeatherEdgesBucket;
426
427 static void feather_bucket_add_edge(FeatherEdgesBucket *bucket, int start, int end)
428 {
429         const int alloc_delta = 20;
430
431         if (bucket->tot_segment >= bucket->alloc_segment) {
432                 if (!bucket->segments) {
433                         bucket->segments = MEM_callocN(alloc_delta * sizeof(*bucket->segments), "feather bucket segments");
434                 }
435                 else {
436                         bucket->segments = MEM_reallocN(bucket->segments,
437                                         (alloc_delta + bucket->tot_segment) * sizeof(*bucket->segments));
438                 }
439
440                 bucket->alloc_segment += alloc_delta;
441         }
442
443         bucket->segments[bucket->tot_segment][0] = start;
444         bucket->segments[bucket->tot_segment][1] = end;
445
446         bucket->tot_segment++;
447 }
448
449 static void feather_bucket_check_intersect(float (*feather_points)[2], int tot_feather_point, FeatherEdgesBucket *bucket,
450                                            int cur_a, int cur_b)
451 {
452         int i;
453
454         float *v1 = (float *) feather_points[cur_a];
455         float *v2 = (float *) feather_points[cur_b];
456
457         for (i = 0; i< bucket->tot_segment; i++) {
458                 int check_a = bucket->segments[i][0];
459                 int check_b = bucket->segments[i][1];
460
461                 float *v3 = (float *) feather_points[check_a];
462                 float *v4 = (float *) feather_points[check_b];
463
464                 if (check_a >= cur_a - 1 || cur_b == check_a)
465                         continue;
466
467                 if (isect_seg_seg_v2(v1, v2, v3, v4)) {
468                         int k, len;
469                         float p[2];
470
471                         isect_seg_seg_v2_point(v1, v2, v3, v4, p);
472
473                         /* TODO: for now simply choose the shortest loop, could be made smarter in some way */
474                         len = cur_a - check_b;
475                         if (len < tot_feather_point - len) {
476                                 for (k = check_b; k <= cur_a; k++) {
477                                         copy_v2_v2(feather_points[k], p);
478                                 }
479                         }
480                         else {
481                                 if (cur_b < check_a) {
482                                         /* special case when intersection happens with first segment */
483                                         for (k = cur_b; k <= check_a; k++) {
484                                                 copy_v2_v2(feather_points[k], p);
485                                         }
486                                 }
487                                 else {
488                                         for (k = 0; k <= check_a; k++) {
489                                                 copy_v2_v2(feather_points[k], p);
490                                         }
491
492                                         for (k = cur_b; k < tot_feather_point; k++) {
493                                                 copy_v2_v2(feather_points[k], p);
494                                         }
495                                 }
496                         }
497
498                         break;
499                 }
500         }
501 }
502
503 static int feather_bucket_index_from_coord(float co[2], float min[2], float max[2],
504                                            const int buckets_per_side, const float bucket_size)
505 {
506 #define BUCKET_SIDE_INDEX(co, min, max) ((int) ((co - min) / (max - min) / bucket_size))
507
508         int x = BUCKET_SIDE_INDEX(co[0], min[0], max[0]);
509         int y = BUCKET_SIDE_INDEX(co[1], min[1], max[1]);
510
511         x = MIN2(x, buckets_per_side - 1);
512         y = MIN2(y, buckets_per_side - 1);
513
514         return y * buckets_per_side + x;
515 #undef BUCKET_SIDE_INDEX
516 }
517
518 static void spline_feather_collapse_inner_loops(float (*feather_points)[2], int tot_feather_point)
519 {
520 #define BUCKET_INDEX(co) \
521         feather_bucket_index_from_coord(co, min, max, buckets_per_side, bucket_size)
522
523         const int buckets_per_side = 10;
524         const int tot_bucket = buckets_per_side * buckets_per_side;
525         const float bucket_size = 1.0f / buckets_per_side;
526
527         FeatherEdgesBucket *buckets;
528
529         int i;
530         float min[2], max[2];
531
532         /* find min/max corners of mask to build buckets in that space */
533         INIT_MINMAX2(min, max);
534
535         for (i = 0; i < tot_feather_point; i++) {
536                 DO_MINMAX2(feather_points[i], min, max);
537         }
538
539         /* fill in buckets' edges */
540         buckets = MEM_callocN(sizeof(FeatherEdgesBucket) * tot_bucket, "feather buckets");
541
542         for (i = 0; i < tot_feather_point; i++) {
543                 int start = i;
544                 int end = (i + 1) % tot_feather_point;
545
546                 int start_bucket_index = BUCKET_INDEX(feather_points[start]);
547                 int end_bucket_index = BUCKET_INDEX(feather_points[end]);
548
549                 feather_bucket_add_edge(&buckets[start_bucket_index], start, end);
550
551                 if (start_bucket_index != end_bucket_index) {
552                         feather_bucket_add_edge(&buckets[end_bucket_index], start, end);
553                 }
554         }
555
556         /* check all edges for intersection with edges from their buckets */
557         for (i = 0; i < tot_feather_point; i++) {
558                 int cur_a = i;
559                 int cur_b = (i + 1) % tot_feather_point;
560
561                 int start_bucket_index = BUCKET_INDEX(feather_points[cur_a]);
562                 int end_bucket_index = BUCKET_INDEX(feather_points[cur_b]);
563
564                 FeatherEdgesBucket *start_bucket = &buckets[start_bucket_index];
565                 FeatherEdgesBucket *end_bucket = &buckets[end_bucket_index];
566
567                 feather_bucket_check_intersect(feather_points, tot_feather_point, start_bucket, cur_a, cur_b);
568
569                 if (start_bucket != end_bucket)
570                         feather_bucket_check_intersect(feather_points, tot_feather_point, end_bucket, cur_a, cur_b);
571         }
572
573         /* free buckets */
574         for (i = 0; i < tot_bucket; i++) {
575                 if (buckets[i].segments)
576                         MEM_freeN(buckets[i].segments);
577         }
578
579         MEM_freeN(buckets);
580
581 #undef BUCKET_INDEX
582 }
583
584 /**
585  * values align with #BKE_mask_spline_differentiate_with_resolution_ex
586  * when \a resol arguments match.
587  */
588 float (*BKE_mask_spline_feather_differentiated_points_with_resolution_ex(MaskSpline *spline, const int resol,
589                                                                          int *tot_feather_point))[2]
590 {
591         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
592         MaskSplinePoint *point, *prev;
593         float (*feather)[2], (*fp)[2];
594
595         const int tot = BKE_mask_spline_differentiate_calc_total(spline, resol);
596         int a;
597
598         /* tot+1 because of 'forward_diff_bezier' function */
599         feather = fp = MEM_mallocN((tot + 1) * sizeof(*feather), "mask spline feather diff points");
600
601         a = spline->tot_point - 1;
602         if (spline->flag & MASK_SPLINE_CYCLIC)
603                 a++;
604
605         prev = points_array;
606         point = prev + 1;
607
608         while (a--) {
609                 /* BezTriple *prevbezt; */  /* UNUSED */
610                 /* BezTriple *bezt; */      /* UNUSED */
611                 int j;
612
613                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC))
614                         point = points_array;
615
616
617                 /* prevbezt = &prev->bezt; */
618                 /* bezt = &point->bezt; */
619
620                 for (j = 0; j < resol; j++, fp++) {
621                         float u = (float) j / resol, weight;
622                         float co[2], n[2];
623
624                         /* TODO - these calls all calculate similar things
625                          * could be unified for some speed */
626                         BKE_mask_point_segment_co(spline, prev, u, co);
627                         BKE_mask_point_normal(spline, prev, u, n);
628                         weight = BKE_mask_point_weight(spline, prev, u);
629
630                         madd_v2_v2v2fl(*fp, co, n, weight);
631                 }
632
633                 if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC) == 0) {
634                         float u = 1.0f, weight;
635                         float co[2], n[2];
636
637                         BKE_mask_point_segment_co(spline, prev, u, co);
638                         BKE_mask_point_normal(spline, prev, u, n);
639                         weight = BKE_mask_point_weight(spline, prev, u);
640
641                         madd_v2_v2v2fl(*fp, co, n, weight);
642                 }
643
644                 prev = point;
645                 point++;
646         }
647
648         *tot_feather_point = tot;
649
650         spline_feather_collapse_inner_loops(feather, tot);
651
652         return feather;
653 }
654
655 float (*BKE_mask_spline_feather_differentiated_points_with_resolution(MaskSpline *spline, int width, int height,
656                                                                       int *tot_feather_point))[2]
657 {
658         int resol = BKE_mask_spline_feather_resolution(spline, width, height);
659
660         return BKE_mask_spline_feather_differentiated_points_with_resolution_ex(spline, resol, tot_feather_point);
661 }
662
663 float (*BKE_mask_spline_feather_differentiated_points(MaskSpline *spline, int *tot_feather_point))[2]
664 {
665         return BKE_mask_spline_feather_differentiated_points_with_resolution(spline, 0, 0, tot_feather_point);
666 }
667
668 float (*BKE_mask_spline_feather_points(MaskSpline *spline, int *tot_feather_point))[2]
669 {
670         MaskSplinePoint *points_array = BKE_mask_spline_point_array(spline);
671
672         int i, tot = 0;
673         float (*feather)[2], (*fp)[2];
674
675         /* count */
676         for (i = 0; i < spline->tot_point; i++) {
677                 MaskSplinePoint *point = &points_array[i];
678
679                 tot += point->tot_uw + 1;
680         }
681
682         /* create data */
683         feather = fp = MEM_mallocN(tot * sizeof(*feather), "mask spline feather points");
684
685         for (i = 0; i < spline->tot_point; i++) {
686                 MaskSplinePoint *point = &points_array[i];
687                 BezTriple *bezt = &point->bezt;
688                 float weight, n[2];
689                 int j;
690
691                 BKE_mask_point_normal(spline, point, 0.0f, n);
692                 weight = BKE_mask_point_weight(spline, point, 0.0f);
693
694                 madd_v2_v2v2fl(*fp, bezt->vec[1], n, weight);
695                 fp++;
696
697                 for (j = 0; j < point->tot_uw; j++) {
698                         float u = point->uw[j].u;
699                         float co[2];
700
701                         BKE_mask_point_segment_co(spline, point, u, co);
702                         BKE_mask_point_normal(spline, point, u, n);
703                         weight = BKE_mask_point_weight(spline, point, u);
704
705                         madd_v2_v2v2fl(*fp, co, n, weight);
706                         fp++;
707                 }
708         }
709
710         *tot_feather_point = tot;
711
712         return feather;
713 }
714
715 void BKE_mask_point_direction_switch(MaskSplinePoint *point)
716 {
717         const int tot_uw = point->tot_uw;
718         const int tot_uw_half = tot_uw / 2;
719         int i;
720
721         float co_tmp[2];
722
723         /* swap handles */
724         copy_v2_v2(co_tmp, point->bezt.vec[0]);
725         copy_v2_v2(point->bezt.vec[0], point->bezt.vec[2]);
726         copy_v2_v2(point->bezt.vec[2], co_tmp);
727         /* in this case the flags are unlikely to be different but swap anyway */
728         SWAP(char, point->bezt.f1, point->bezt.f3);
729         SWAP(char, point->bezt.h1, point->bezt.h2);
730
731
732         /* swap UW's */
733         if (tot_uw > 1) {
734                 /* count */
735                 for (i = 0; i < tot_uw_half; i++) {
736                         MaskSplinePointUW *uw_a = &point->uw[i];
737                         MaskSplinePointUW *uw_b = &point->uw[tot_uw - (i + 1)];
738                         SWAP(MaskSplinePointUW, *uw_a, *uw_b);
739                 }
740         }
741
742         for (i = 0; i < tot_uw; i++) {
743                 MaskSplinePointUW *uw = &point->uw[i];
744                 uw->u = 1.0f - uw->u;
745         }
746 }
747
748 void BKE_mask_spline_direction_switch(MaskLayer *masklay, MaskSpline *spline)
749 {
750         const int tot_point = spline->tot_point;
751         const int tot_point_half = tot_point / 2;
752         int i, i_prev;
753
754         if (tot_point < 2) {
755                 return;
756         }
757
758         /* count */
759         for (i = 0; i < tot_point_half; i++) {
760                 MaskSplinePoint *point_a = &spline->points[i];
761                 MaskSplinePoint *point_b = &spline->points[tot_point - (i + 1)];
762                 SWAP(MaskSplinePoint, *point_a, *point_b);
763         }
764
765         /* correct UW's */
766         i_prev = tot_point - 1;
767         for (i = 0; i < tot_point; i++) {
768
769                 BKE_mask_point_direction_switch(&spline->points[i]);
770
771                 SWAP(MaskSplinePointUW *, spline->points[i].uw,     spline->points[i_prev].uw);
772                 SWAP(int,                 spline->points[i].tot_uw, spline->points[i_prev].tot_uw);
773
774                 i_prev = i;
775         }
776
777         /* correct animation */
778         if (masklay->splines_shapes.first) {
779                 MaskLayerShape *masklay_shape;
780
781                 const int spline_index = BKE_mask_layer_shape_spline_to_index(masklay, spline);
782
783                 for (masklay_shape = masklay->splines_shapes.first;
784                      masklay_shape;
785                      masklay_shape = masklay_shape->next)
786                 {
787                         MaskLayerShapeElem *fp_arr = (MaskLayerShapeElem *)masklay_shape->data;
788
789                         for (i = 0; i < tot_point_half; i++) {
790                                 MaskLayerShapeElem *fp_a = &fp_arr[spline_index +              (i)     ];
791                                 MaskLayerShapeElem *fp_b = &fp_arr[spline_index + (tot_point - (i + 1))];
792                                 SWAP(MaskLayerShapeElem, *fp_a, *fp_b);
793                         }
794                 }
795         }
796 }
797
798
799 float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point,
800                                  float start_u, const float co[2], const eMaskSign sign)
801 {
802         const float proj_eps         = 1e-3;
803         const float proj_eps_squared = proj_eps * proj_eps;
804         const int N = 1000;
805         float u = -1.0f, du = 1.0f / N, u1 = start_u, u2 = start_u;
806         float ang = -1.0f;
807
808         BLI_assert(ABS(sign) <= 1); /* (-1, 0, 1) */
809
810         while (u1 > 0.0f || u2 < 1.0f) {
811                 float n1[2], n2[2], co1[2], co2[2];
812                 float v1[2], v2[2];
813                 float ang1, ang2;
814
815                 if (u1 >= 0.0f) {
816                         BKE_mask_point_segment_co(spline, point, u1, co1);
817                         BKE_mask_point_normal(spline, point, u1, n1);
818                         sub_v2_v2v2(v1, co, co1);
819
820                         if ((sign == MASK_PROJ_ANY) ||
821                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v1, n1) <= 0.0f)) ||
822                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v1, n1) >= 0.0f)))
823                         {
824
825                                 if (len_squared_v2(v1) > proj_eps_squared) {
826                                         ang1 = angle_v2v2(v1, n1);
827                                         if (ang1 > M_PI / 2.0f)
828                                                 ang1 = M_PI  - ang1;
829
830                                         if (ang < 0.0f || ang1 < ang) {
831                                                 ang = ang1;
832                                                 u = u1;
833                                         }
834                                 }
835                                 else {
836                                         u = u1;
837                                         break;
838                                 }
839                         }
840                 }
841
842                 if (u2 <= 1.0f) {
843                         BKE_mask_point_segment_co(spline, point, u2, co2);
844                         BKE_mask_point_normal(spline, point, u2, n2);
845                         sub_v2_v2v2(v2, co, co2);
846
847                         if ((sign == MASK_PROJ_ANY) ||
848                             ((sign == MASK_PROJ_NEG) && (dot_v2v2(v2, n2) <= 0.0f)) ||
849                             ((sign == MASK_PROJ_POS) && (dot_v2v2(v2, n2) >= 0.0f)))
850                         {
851
852                                 if (len_squared_v2(v2) > proj_eps_squared) {
853                                         ang2 = angle_v2v2(v2, n2);
854                                         if (ang2 > M_PI / 2.0f)
855                                                 ang2 = M_PI  - ang2;
856
857                                         if (ang2 < ang) {
858                                                 ang = ang2;
859                                                 u = u2;
860                                         }
861                                 }
862                                 else {
863                                         u = u2;
864                                         break;
865                                 }
866                         }
867                 }
868
869                 u1 -= du;
870                 u2 += du;
871         }
872
873         return u;
874 }
875
876 /* point */
877
878 int BKE_mask_point_has_handle(MaskSplinePoint *point)
879 {
880         BezTriple *bezt = &point->bezt;
881
882         return bezt->h1 == HD_ALIGN;
883 }
884
885 void BKE_mask_point_handle(MaskSplinePoint *point, float handle[2])
886 {
887         float vec[2];
888
889         sub_v2_v2v2(vec, point->bezt.vec[0], point->bezt.vec[1]);
890
891         handle[0] = (point->bezt.vec[1][0] + vec[1]);
892         handle[1] = (point->bezt.vec[1][1] - vec[0]);
893 }
894
895 void BKE_mask_point_set_handle(MaskSplinePoint *point, float loc[2], int keep_direction,
896                                float orig_handle[2], float orig_vec[3][3])
897 {
898         BezTriple *bezt = &point->bezt;
899         float v1[2], v2[2], vec[2];
900
901         if (keep_direction) {
902                 sub_v2_v2v2(v1, loc, orig_vec[1]);
903                 sub_v2_v2v2(v2, orig_handle, orig_vec[1]);
904
905                 project_v2_v2v2(vec, v1, v2);
906
907                 if (dot_v2v2(v2, vec) > 0) {
908                         float len = len_v2(vec);
909
910                         sub_v2_v2v2(v1, orig_vec[0], orig_vec[1]);
911
912                         mul_v2_fl(v1, len / len_v2(v1));
913
914                         add_v2_v2v2(bezt->vec[0], bezt->vec[1], v1);
915                         sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v1);
916                 }
917                 else {
918                         copy_v3_v3(bezt->vec[0], bezt->vec[1]);
919                         copy_v3_v3(bezt->vec[2], bezt->vec[1]);
920                 }
921         }
922         else {
923                 sub_v2_v2v2(v1, loc, bezt->vec[1]);
924
925                 v2[0] = -v1[1];
926                 v2[1] =  v1[0];
927
928                 add_v2_v2v2(bezt->vec[0], bezt->vec[1], v2);
929                 sub_v2_v2v2(bezt->vec[2], bezt->vec[1], v2);
930         }
931 }
932
933 float *BKE_mask_point_segment_feather_diff_with_resolution(MaskSpline *spline, MaskSplinePoint *point,
934                                                            int width, int height,
935                                                            int *tot_feather_point)
936 {
937         float *feather, *fp;
938         int i, resol = BKE_mask_spline_feather_resolution(spline, width, height);
939
940         feather = fp = MEM_callocN(2 * resol * sizeof(float), "mask point spline feather diff points");
941
942         for (i = 0; i < resol; i++, fp += 2) {
943                 float u = (float)(i % resol) / resol, weight;
944                 float co[2], n[2];
945
946                 BKE_mask_point_segment_co(spline, point, u, co);
947                 BKE_mask_point_normal(spline, point, u, n);
948                 weight = BKE_mask_point_weight(spline, point, u);
949
950                 fp[0] = co[0] + n[0] * weight;
951                 fp[1] = co[1] + n[1] * weight;
952         }
953
954         *tot_feather_point = resol;
955
956         return feather;
957 }
958
959 float *BKE_mask_point_segment_feather_diff(MaskSpline *spline, MaskSplinePoint *point, int *tot_feather_point)
960 {
961         return BKE_mask_point_segment_feather_diff_with_resolution(spline, point, 0, 0, tot_feather_point);
962 }
963
964 float *BKE_mask_point_segment_diff_with_resolution(MaskSpline *spline, MaskSplinePoint *point,
965                                                    int width, int height, int *tot_diff_point)
966 {
967         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
968
969         BezTriple *bezt, *bezt_next;
970         float *diff_points, *fp;
971         int j, resol = BKE_mask_spline_resolution(spline, width, height);
972
973         bezt = &point->bezt;
974         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
975
976         if (!bezt_next)
977                 return NULL;
978
979         /* resol+1 because of 'forward_diff_bezier' function */
980         *tot_diff_point = resol + 1;
981         diff_points = fp = MEM_callocN((resol + 1) * 2 * sizeof(float), "mask segment vets");
982
983         for (j = 0; j < 2; j++) {
984                 BKE_curve_forward_diff_bezier(bezt->vec[1][j], bezt->vec[2][j],
985                                               bezt_next->vec[0][j], bezt_next->vec[1][j],
986                                               fp + j, resol, 2 * sizeof(float));
987         }
988
989         copy_v2_v2(fp + 2 * resol, bezt_next->vec[1]);
990
991         return diff_points;
992 }
993
994 float *BKE_mask_point_segment_diff(MaskSpline *spline, MaskSplinePoint *point, int *tot_diff_point)
995 {
996         return BKE_mask_point_segment_diff_with_resolution(spline, point, 0, 0, tot_diff_point);
997 }
998
999 void BKE_mask_point_segment_co(MaskSpline *spline, MaskSplinePoint *point, float u, float co[2])
1000 {
1001         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1002
1003         BezTriple *bezt = &point->bezt, *bezt_next;
1004         float q0[2], q1[2], q2[2], r0[2], r1[2];
1005
1006         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
1007
1008         if (!bezt_next) {
1009                 copy_v2_v2(co, bezt->vec[1]);
1010                 return;
1011         }
1012
1013         interp_v2_v2v2(q0, bezt->vec[1], bezt->vec[2], u);
1014         interp_v2_v2v2(q1, bezt->vec[2], bezt_next->vec[0], u);
1015         interp_v2_v2v2(q2, bezt_next->vec[0], bezt_next->vec[1], u);
1016
1017         interp_v2_v2v2(r0, q0, q1, u);
1018         interp_v2_v2v2(r1, q1, q2, u);
1019
1020         interp_v2_v2v2(co, r0, r1, u);
1021 }
1022
1023 void BKE_mask_point_normal(MaskSpline *spline, MaskSplinePoint *point, float u, float n[2])
1024 {
1025         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1026
1027         BezTriple *bezt = &point->bezt, *bezt_next;
1028         float q0[2], q1[2], q2[2], r0[2], r1[2], vec[2];
1029
1030         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
1031
1032         if (!bezt_next) {
1033                 BKE_mask_point_handle(point, vec);
1034
1035                 sub_v2_v2v2(n, vec, bezt->vec[1]);
1036                 normalize_v2(n);
1037                 return;
1038         }
1039
1040         interp_v2_v2v2(q0, bezt->vec[1], bezt->vec[2], u);
1041         interp_v2_v2v2(q1, bezt->vec[2], bezt_next->vec[0], u);
1042         interp_v2_v2v2(q2, bezt_next->vec[0], bezt_next->vec[1], u);
1043
1044         interp_v2_v2v2(r0, q0, q1, u);
1045         interp_v2_v2v2(r1, q1, q2, u);
1046
1047         sub_v2_v2v2(vec, r1, r0);
1048
1049         n[0] = -vec[1];
1050         n[1] =  vec[0];
1051
1052         normalize_v2(n);
1053 }
1054
1055 static float mask_point_interp_weight(BezTriple *bezt, BezTriple *bezt_next, const float u)
1056 {
1057         return (bezt->weight * (1.0f - u)) + (bezt_next->weight * u);
1058 }
1059
1060 float BKE_mask_point_weight_scalar(MaskSpline *spline, MaskSplinePoint *point, const float u)
1061 {
1062         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1063         BezTriple *bezt = &point->bezt, *bezt_next;
1064
1065         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
1066
1067         if (!bezt_next) {
1068                 return bezt->weight;
1069         }
1070         else if (u <= 0.0) {
1071                 return bezt->weight;
1072         }
1073         else if (u >= 1.0f) {
1074                 return bezt_next->weight;
1075         }
1076         else {
1077                 return mask_point_interp_weight(bezt, bezt_next, u);
1078         }
1079 }
1080
1081 float BKE_mask_point_weight(MaskSpline *spline, MaskSplinePoint *point, const float u)
1082 {
1083         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1084         BezTriple *bezt = &point->bezt, *bezt_next;
1085
1086         bezt_next = mask_spline_point_next_bezt(spline, points_array, point);
1087
1088         if (!bezt_next) {
1089                 return bezt->weight;
1090         }
1091         else if (u <= 0.0) {
1092                 return bezt->weight;
1093         }
1094         else if (u >= 1.0f) {
1095                 return bezt_next->weight;
1096         }
1097         else {
1098                 float cur_u = 0.0f, cur_w = 0.0f, next_u = 0.0f, next_w = 0.0f, fac; /* Quite warnings */
1099                 int i;
1100
1101                 for (i = 0; i < point->tot_uw + 1; i++) {
1102
1103                         if (i == 0) {
1104                                 cur_u = 0.0f;
1105                                 cur_w = 1.0f; /* mask_point_interp_weight will scale it */
1106                         }
1107                         else {
1108                                 cur_u = point->uw[i - 1].u;
1109                                 cur_w = point->uw[i - 1].w;
1110                         }
1111
1112                         if (i == point->tot_uw) {
1113                                 next_u = 1.0f;
1114                                 next_w = 1.0f; /* mask_point_interp_weight will scale it */
1115                         }
1116                         else {
1117                                 next_u = point->uw[i].u;
1118                                 next_w = point->uw[i].w;
1119                         }
1120
1121                         if (u >= cur_u && u <= next_u) {
1122                                 break;
1123                         }
1124                 }
1125
1126                 fac = (u - cur_u) / (next_u - cur_u);
1127
1128                 cur_w  *= mask_point_interp_weight(bezt, bezt_next, cur_u);
1129                 next_w *= mask_point_interp_weight(bezt, bezt_next, next_u);
1130
1131                 if (spline->weight_interp == MASK_SPLINE_INTERP_EASE) {
1132                         return cur_w + (next_w - cur_w) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
1133                 }
1134                 else {
1135                         return (1.0f - fac) * cur_w + fac * next_w;
1136                 }
1137         }
1138 }
1139
1140 MaskSplinePointUW *BKE_mask_point_sort_uw(MaskSplinePoint *point, MaskSplinePointUW *uw)
1141 {
1142         if (point->tot_uw > 1) {
1143                 int idx = uw - point->uw;
1144
1145                 if (idx > 0 && point->uw[idx - 1].u > uw->u) {
1146                         while (idx > 0 && point->uw[idx - 1].u > point->uw[idx].u) {
1147                                 SWAP(MaskSplinePointUW, point->uw[idx - 1], point->uw[idx]);
1148                                 idx--;
1149                         }
1150                 }
1151
1152                 if (idx < point->tot_uw - 1 && point->uw[idx + 1].u < uw->u) {
1153                         while (idx < point->tot_uw - 1 && point->uw[idx + 1].u < point->uw[idx].u) {
1154                                 SWAP(MaskSplinePointUW, point->uw[idx + 1], point->uw[idx]);
1155                                 idx++;
1156                         }
1157                 }
1158
1159                 return &point->uw[idx];
1160         }
1161
1162         return uw;
1163 }
1164
1165 void BKE_mask_point_add_uw(MaskSplinePoint *point, float u, float w)
1166 {
1167         if (!point->uw)
1168                 point->uw = MEM_callocN(sizeof(*point->uw), "mask point uw");
1169         else
1170                 point->uw = MEM_reallocN(point->uw, (point->tot_uw + 1) * sizeof(*point->uw));
1171
1172         point->uw[point->tot_uw].u = u;
1173         point->uw[point->tot_uw].w = w;
1174
1175         point->tot_uw++;
1176
1177         BKE_mask_point_sort_uw(point, &point->uw[point->tot_uw - 1]);
1178 }
1179
1180 void BKE_mask_point_select_set(MaskSplinePoint *point, const short do_select)
1181 {
1182         int i;
1183
1184         if (do_select) {
1185                 MASKPOINT_SEL_ALL(point);
1186         }
1187         else {
1188                 MASKPOINT_DESEL_ALL(point);
1189         }
1190
1191         for (i = 0; i < point->tot_uw; i++) {
1192                 if (do_select) {
1193                         point->uw[i].flag |= SELECT;
1194                 }
1195                 else {
1196                         point->uw[i].flag &= ~SELECT;
1197                 }
1198         }
1199 }
1200
1201 void BKE_mask_point_select_set_handle(MaskSplinePoint *point, const short do_select)
1202 {
1203         if (do_select) {
1204                 MASKPOINT_SEL_HANDLE(point);
1205         }
1206         else {
1207                 MASKPOINT_DESEL_HANDLE(point);
1208         }
1209 }
1210
1211 /* only mask block itself */
1212 static Mask *mask_alloc(const char *name)
1213 {
1214         Mask *mask;
1215
1216         mask = BKE_libblock_alloc(&G.main->mask, ID_MSK, name);
1217
1218         return mask;
1219 }
1220
1221 Mask *BKE_mask_new(const char *name)
1222 {
1223         Mask *mask;
1224         char mask_name[MAX_ID_NAME - 2];
1225
1226         if (name && name[0])
1227                 BLI_strncpy(mask_name, name, sizeof(mask_name));
1228         else
1229                 strcpy(mask_name, "Mask");
1230
1231         mask = mask_alloc(mask_name);
1232
1233         /* arbitrary defaults */
1234         mask->sfra = 1;
1235         mask->efra = 100;
1236
1237         return mask;
1238 }
1239
1240 void BKE_mask_point_free(MaskSplinePoint *point)
1241 {
1242         if (point->uw)
1243                 MEM_freeN(point->uw);
1244 }
1245
1246 void BKE_mask_spline_free(MaskSpline *spline)
1247 {
1248         int i = 0;
1249
1250         for (i = 0; i < spline->tot_point; i++) {
1251                 MaskSplinePoint *point;
1252                 point = &spline->points[i];
1253                 BKE_mask_point_free(point);
1254
1255                 if (spline->points_deform) {
1256                         point = &spline->points_deform[i];
1257                         BKE_mask_point_free(point);
1258                 }
1259         }
1260
1261         MEM_freeN(spline->points);
1262
1263         if (spline->points_deform) {
1264                 MEM_freeN(spline->points_deform);
1265         }
1266
1267         MEM_freeN(spline);
1268 }
1269
1270 static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot_point)
1271 {
1272         MaskSplinePoint *npoints;
1273         int i;
1274
1275         npoints = MEM_dupallocN(points);
1276
1277         for (i = 0; i < tot_point; i++) {
1278                 MaskSplinePoint *point = &npoints[i];
1279
1280                 if (point->uw)
1281                         point->uw = MEM_dupallocN(point->uw);
1282         }
1283
1284         return npoints;
1285 }
1286
1287 MaskSpline *BKE_mask_spline_copy(MaskSpline *spline)
1288 {
1289         MaskSpline *nspline = MEM_callocN(sizeof(MaskSpline), "new spline");
1290
1291         *nspline = *spline;
1292
1293         nspline->points_deform = NULL;
1294         nspline->points = mask_spline_points_copy(spline->points, spline->tot_point);
1295
1296         if (spline->points_deform) {
1297                 nspline->points_deform = mask_spline_points_copy(spline->points_deform, spline->tot_point);
1298         }
1299
1300         return nspline;
1301 }
1302
1303 /* note: does NOT add to the list */
1304 MaskLayerShape *BKE_mask_layer_shape_alloc(MaskLayer *masklay, const int frame)
1305 {
1306         MaskLayerShape *masklay_shape;
1307         int tot_vert = BKE_mask_layer_shape_totvert(masklay);
1308
1309         masklay_shape = MEM_mallocN(sizeof(MaskLayerShape), __func__);
1310         masklay_shape->frame = frame;
1311         masklay_shape->tot_vert = tot_vert;
1312         masklay_shape->data = MEM_mallocN(tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
1313
1314         return masklay_shape;
1315 }
1316
1317 void BKE_mask_layer_shape_free(MaskLayerShape *masklay_shape)
1318 {
1319         MEM_freeN(masklay_shape->data);
1320
1321         MEM_freeN(masklay_shape);
1322 }
1323
1324 /** \brief Free all animation keys for a mask layer
1325  */
1326 void BKE_mask_layer_free_shapes(MaskLayer *masklay)
1327 {
1328         MaskLayerShape *masklay_shape;
1329
1330         /* free animation data */
1331         masklay_shape = masklay->splines_shapes.first;
1332         while (masklay_shape) {
1333                 MaskLayerShape *next_masklay_shape = masklay_shape->next;
1334
1335                 BLI_remlink(&masklay->splines_shapes, masklay_shape);
1336                 BKE_mask_layer_shape_free(masklay_shape);
1337
1338                 masklay_shape = next_masklay_shape;
1339         }
1340 }
1341
1342 void BKE_mask_layer_free(MaskLayer *masklay)
1343 {
1344         MaskSpline *spline;
1345
1346         /* free splines */
1347         spline = masklay->splines.first;
1348         while (spline) {
1349                 MaskSpline *next_spline = spline->next;
1350
1351                 BLI_remlink(&masklay->splines, spline);
1352                 BKE_mask_spline_free(spline);
1353
1354                 spline = next_spline;
1355         }
1356
1357         /* free animation data */
1358         BKE_mask_layer_free_shapes(masklay);
1359
1360         MEM_freeN(masklay);
1361 }
1362
1363
1364 void BKE_mask_layer_free_list(ListBase *masklayers)
1365 {
1366         MaskLayer *masklay = masklayers->first;
1367
1368         while (masklay) {
1369                 MaskLayer *masklay_next = masklay->next;
1370
1371                 BLI_remlink(masklayers, masklay);
1372                 BKE_mask_layer_free(masklay);
1373
1374                 masklay = masklay_next;
1375         }
1376
1377 }
1378
1379 #ifdef USE_MANGO_MASK_CACHE_HACK
1380 void BKE_mask_raster_cache_free(Mask *mask)
1381 {
1382         MaskRasterCache *cache = mask->raster_cache;
1383
1384         if (cache) {
1385                 MaskLayer *layer;
1386
1387                 layer = cache->layers.first;
1388                 while (layer) {
1389                         MaskLayer *layer_next = layer->next;
1390
1391                         BKE_mask_layer_free(layer);
1392                         layer = layer_next;
1393                 }
1394
1395                 MEM_freeN(cache->buffer);
1396                 MEM_freeN(cache);
1397
1398                 mask->raster_cache = NULL;
1399         }
1400 }
1401 #endif
1402
1403 void BKE_mask_free(Mask *mask)
1404 {
1405         BKE_mask_layer_free_list(&mask->masklayers);
1406
1407 #ifdef USE_MANGO_MASK_CACHE_HACK
1408         if (mask->raster_cache) {
1409                 BKE_mask_raster_cache_free(mask);
1410
1411                 mask->raster_cache = NULL;
1412         }
1413 #endif
1414 }
1415
1416 void BKE_mask_unlink(Main *bmain, Mask *mask)
1417 {
1418         bScreen *scr;
1419         ScrArea *area;
1420         SpaceLink *sl;
1421
1422         for (scr = bmain->screen.first; scr; scr = scr->id.next) {
1423                 for (area = scr->areabase.first; area; area = area->next) {
1424                         for (sl = area->spacedata.first; sl; sl = sl->next) {
1425                                 if (sl->spacetype == SPACE_CLIP) {
1426                                         SpaceClip *sc = (SpaceClip *) sl;
1427
1428                                         if (sc->mask == mask)
1429                                                 sc->mask = NULL;
1430                                 }
1431                         }
1432                 }
1433         }
1434
1435         mask->id.us = 0;
1436 }
1437
1438 void BKE_mask_coord_from_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1439 {
1440         int width, height;
1441
1442         /* scaling for the clip */
1443         BKE_movieclip_get_size(clip, user, &width, &height);
1444
1445         if (width == height) {
1446                 r_co[0] = co[0];
1447                 r_co[1] = co[1];
1448         }
1449         else if (width < height) {
1450                 r_co[0] = ((co[0] - 0.5f) * ((float)width / (float)height)) + 0.5f;
1451                 r_co[1] = co[1];
1452         }
1453         else { /* (width > height) */
1454                 r_co[0] = co[0];
1455                 r_co[1] = ((co[1] - 0.5f) * ((float)height / (float)width)) + 0.5f;
1456         }
1457 }
1458
1459 /* as above but divide */
1460 void BKE_mask_coord_to_movieclip(MovieClip *clip, MovieClipUser *user, float r_co[2], const float co[2])
1461 {
1462         int width, height;
1463
1464         /* scaling for the clip */
1465         BKE_movieclip_get_size(clip, user, &width, &height);
1466
1467         if (width == height) {
1468                 r_co[0] = co[0];
1469                 r_co[1] = co[1];
1470         }
1471         else if (width < height) {
1472                 r_co[0] = ((co[0] - 0.5f) / ((float)width / (float)height)) + 0.5f;
1473                 r_co[1] = co[1];
1474         }
1475         else { /* (width > height) */
1476                 r_co[0] = co[0];
1477                 r_co[1] = ((co[1] - 0.5f) / ((float)height / (float)width)) + 0.5f;
1478         }
1479 }
1480
1481 static int BKE_mask_evaluate_parent(MaskParent *parent, float ctime, float r_co[2])
1482 {
1483         if (!parent)
1484                 return FALSE;
1485
1486         if (parent->id_type == ID_MC) {
1487                 if (parent->id) {
1488                         MovieClip *clip = (MovieClip *) parent->id;
1489                         MovieTracking *tracking = (MovieTracking *) &clip->tracking;
1490                         MovieTrackingObject *ob = BKE_tracking_object_get_named(tracking, parent->parent);
1491
1492                         if (ob) {
1493                                 MovieTrackingTrack *track = BKE_tracking_track_get_named(tracking, ob, parent->sub_parent);
1494                                 float clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, ctime);
1495
1496                                 MovieClipUser user = {0};
1497                                 user.framenr = ctime;
1498
1499                                 if (track) {
1500                                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, clip_framenr);
1501                                         float marker_pos_ofs[2];
1502                                         add_v2_v2v2(marker_pos_ofs, marker->pos, track->offset);
1503                                         BKE_mask_coord_from_movieclip(clip, &user, r_co, marker_pos_ofs);
1504
1505                                         return TRUE;
1506                                 }
1507                         }
1508                 }
1509         }
1510
1511         return FALSE;
1512 }
1513
1514 int BKE_mask_evaluate_parent_delta(MaskParent *parent, float ctime, float r_delta[2])
1515 {
1516         float parent_co[2];
1517
1518         if (BKE_mask_evaluate_parent(parent, ctime, parent_co)) {
1519                 sub_v2_v2v2(r_delta, parent_co, parent->parent_orig);
1520                 return TRUE;
1521         }
1522         else {
1523                 return FALSE;
1524         }
1525 }
1526
1527 static void mask_calc_point_handle(MaskSplinePoint *point, MaskSplinePoint *point_prev, MaskSplinePoint *point_next)
1528 {
1529         BezTriple *bezt = &point->bezt;
1530         BezTriple *bezt_prev = NULL, *bezt_next = NULL;
1531         //int handle_type = bezt->h1;
1532
1533         if (point_prev)
1534                 bezt_prev = &point_prev->bezt;
1535
1536         if (point_next)
1537                 bezt_next = &point_next->bezt;
1538
1539 #if 1
1540         if (bezt_prev || bezt_next) {
1541                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1542         }
1543 #else
1544         if (handle_type == HD_VECT) {
1545                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1546         }
1547         else if (handle_type == HD_AUTO) {
1548                 BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
1549         }
1550         else if (handle_type == HD_ALIGN) {
1551                 float v1[3], v2[3];
1552                 float vec[3], h[3];
1553
1554                 sub_v3_v3v3(v1, bezt->vec[0], bezt->vec[1]);
1555                 sub_v3_v3v3(v2, bezt->vec[2], bezt->vec[1]);
1556                 add_v3_v3v3(vec, v1, v2);
1557
1558                 if (len_v3(vec) > 1e-3) {
1559                         h[0] = vec[1];
1560                         h[1] = -vec[0];
1561                         h[2] = 0.0f;
1562                 }
1563                 else {
1564                         copy_v3_v3(h, v1);
1565                 }
1566
1567                 add_v3_v3v3(bezt->vec[0], bezt->vec[1], h);
1568                 sub_v3_v3v3(bezt->vec[2], bezt->vec[1], h);
1569         }
1570 #endif
1571 }
1572
1573 void BKE_mask_get_handle_point_adjacent(MaskSpline *spline, MaskSplinePoint *point,
1574                                         MaskSplinePoint **r_point_prev, MaskSplinePoint **r_point_next)
1575 {
1576         /* TODO, could avoid calling this at such low level */
1577         MaskSplinePoint *points_array = BKE_mask_spline_point_array_from_point(spline, point);
1578
1579         *r_point_prev = mask_spline_point_prev(spline, points_array, point);
1580         *r_point_next = mask_spline_point_next(spline, points_array, point);
1581 }
1582
1583 /* calculates the tanget of a point by its previous and next
1584  * (ignoring handles - as if its a poly line) */
1585 void BKE_mask_calc_tangent_polyline(MaskSpline *spline, MaskSplinePoint *point, float t[2])
1586 {
1587         float tvec_a[2], tvec_b[2];
1588
1589         MaskSplinePoint *point_prev, *point_next;
1590
1591         BKE_mask_get_handle_point_adjacent(spline, point,
1592                                            &point_prev, &point_next);
1593
1594         if (point_prev) {
1595                 sub_v2_v2v2(tvec_a, point->bezt.vec[1], point_prev->bezt.vec[1]);
1596                 normalize_v2(tvec_a);
1597         }
1598         else {
1599                 zero_v2(tvec_a);
1600         }
1601
1602         if (point_next) {
1603                 sub_v2_v2v2(tvec_b, point_next->bezt.vec[1], point->bezt.vec[1]);
1604                 normalize_v2(tvec_b);
1605         }
1606         else {
1607                 zero_v2(tvec_b);
1608         }
1609
1610         add_v2_v2v2(t, tvec_a, tvec_b);
1611         normalize_v2(t);
1612 }
1613
1614 void BKE_mask_calc_handle_point(MaskSpline *spline, MaskSplinePoint *point)
1615 {
1616         MaskSplinePoint *point_prev, *point_next;
1617
1618         BKE_mask_get_handle_point_adjacent(spline, point,
1619                                            &point_prev, &point_next);
1620
1621         mask_calc_point_handle(point, point_prev, point_next);
1622 }
1623
1624 static void enforce_dist_v2_v2fl(float v1[2], const float v2[2], const float dist)
1625 {
1626         if (!equals_v2v2(v2, v1)) {
1627                 float nor[2];
1628
1629                 sub_v2_v2v2(nor, v1, v2);
1630                 normalize_v2(nor);
1631                 madd_v2_v2v2fl(v1, v2, nor, dist);
1632         }
1633 }
1634
1635 void BKE_mask_calc_handle_adjacent_interp(MaskSpline *spline, MaskSplinePoint *point, const float u)
1636 {
1637         /* TODO! - make this interpolate between siblings - not always midpoint! */
1638         int length_tot = 0;
1639         float length_average = 0.0f;
1640         float weight_average = 0.0f;
1641
1642
1643         MaskSplinePoint *point_prev, *point_next;
1644
1645         BLI_assert(u >= 0.0f && u <= 1.0f);
1646
1647         BKE_mask_get_handle_point_adjacent(spline, point,
1648                                            &point_prev, &point_next);
1649
1650         if (point_prev && point_next) {
1651                 length_average = ((len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]) * (1.0f - u)) +
1652                                   (len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]) * u));
1653
1654                 weight_average = (point_prev->bezt.weight * (1.0f - u) +
1655                                   point_next->bezt.weight * u);
1656                 length_tot = 1;
1657         }
1658         else {
1659                 if (point_prev) {
1660                         length_average += len_v2v2(point_prev->bezt.vec[0], point_prev->bezt.vec[1]);
1661                         weight_average += point_prev->bezt.weight;
1662                         length_tot++;
1663                 }
1664
1665                 if (point_next) {
1666                         length_average += len_v2v2(point_next->bezt.vec[2], point_next->bezt.vec[1]);
1667                         weight_average += point_next->bezt.weight;
1668                         length_tot++;
1669                 }
1670         }
1671
1672         if (length_tot) {
1673                 length_average /= (float)length_tot;
1674                 weight_average /= (float)length_tot;
1675
1676                 enforce_dist_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1677                 enforce_dist_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1678                 point->bezt.weight = weight_average;
1679         }
1680 }
1681
1682
1683 /**
1684  * \brief Resets auto handles even for non-auto bezier points
1685  *
1686  * Useful for giving sane defaults.
1687  */
1688 void BKE_mask_calc_handle_point_auto(MaskSpline *spline, MaskSplinePoint *point,
1689                                      const short do_recalc_length)
1690 {
1691         MaskSplinePoint *point_prev, *point_next;
1692         const char h_back[2] = {point->bezt.h1, point->bezt.h2};
1693         const float length_average = (do_recalc_length) ? 0.0f /* dummy value */ :
1694                                      (len_v3v3(point->bezt.vec[0], point->bezt.vec[1]) +
1695                                       len_v3v3(point->bezt.vec[1], point->bezt.vec[2])) / 2.0f;
1696
1697         BKE_mask_get_handle_point_adjacent(spline, point,
1698                                            &point_prev, &point_next);
1699
1700         point->bezt.h1 = HD_AUTO;
1701         point->bezt.h2 = HD_AUTO;
1702         mask_calc_point_handle(point, point_prev, point_next);
1703
1704         point->bezt.h1 = h_back[0];
1705         point->bezt.h2 = h_back[1];
1706
1707         /* preserve length by applying it back */
1708         if (do_recalc_length == FALSE) {
1709                 enforce_dist_v2_v2fl(point->bezt.vec[0], point->bezt.vec[1], length_average);
1710                 enforce_dist_v2_v2fl(point->bezt.vec[2], point->bezt.vec[1], length_average);
1711         }
1712 }
1713
1714 void BKE_mask_layer_calc_handles(MaskLayer *masklay)
1715 {
1716         MaskSpline *spline;
1717         for (spline = masklay->splines.first; spline; spline = spline->next) {
1718                 int i;
1719                 for (i = 0; i < spline->tot_point; i++) {
1720                         BKE_mask_calc_handle_point(spline, &spline->points[i]);
1721                 }
1722         }
1723 }
1724
1725 void BKE_mask_layer_calc_handles_deform(MaskLayer *masklay)
1726 {
1727         MaskSpline *spline;
1728         for (spline = masklay->splines.first; spline; spline = spline->next) {
1729                 int i;
1730                 for (i = 0; i < spline->tot_point; i++) {
1731                         BKE_mask_calc_handle_point(spline, &spline->points_deform[i]);
1732                 }
1733         }
1734 }
1735
1736 void BKE_mask_calc_handles(Mask *mask)
1737 {
1738         MaskLayer *masklay;
1739         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1740                 BKE_mask_layer_calc_handles(masklay);
1741         }
1742 }
1743
1744 void BKE_mask_update_deform(Mask *mask)
1745 {
1746         MaskLayer *masklay;
1747
1748         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1749                 MaskSpline *spline;
1750
1751                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1752                         int i;
1753
1754                         for (i = 0; i < spline->tot_point; i++) {
1755                                 const int i_prev = (i - 1) % spline->tot_point;
1756                                 const int i_next = (i + 1) % spline->tot_point;
1757
1758                                 BezTriple *bezt_prev = &spline->points[i_prev].bezt;
1759                                 BezTriple *bezt      = &spline->points[i].bezt;
1760                                 BezTriple *bezt_next = &spline->points[i_next].bezt;
1761
1762                                 BezTriple *bezt_def_prev = &spline->points_deform[i_prev].bezt;
1763                                 BezTriple *bezt_def      = &spline->points_deform[i].bezt;
1764                                 BezTriple *bezt_def_next = &spline->points_deform[i_next].bezt;
1765
1766                                 float w_src[4];
1767                                 int j;
1768
1769                                 for (j = 0; j <= 2; j += 2) { /* (0, 2) */
1770                                         printf("--- %d %d, %d, %d\n", i, j, i_prev, i_next);
1771                                         barycentric_weights_v2(bezt_prev->vec[1], bezt->vec[1], bezt_next->vec[1],
1772                                                                bezt->vec[j], w_src);
1773                                         interp_v3_v3v3v3(bezt_def->vec[j],
1774                                                          bezt_def_prev->vec[1], bezt_def->vec[1], bezt_def_next->vec[1], w_src);
1775                                 }
1776                         }
1777                 }
1778         }
1779 }
1780
1781 void BKE_mask_spline_ensure_deform(MaskSpline *spline)
1782 {
1783         int allocated_points = (MEM_allocN_len(spline->points_deform) / sizeof(*spline->points_deform));
1784         // printf("SPLINE ALLOC %p %d\n", spline->points_deform, allocated_points);
1785
1786         if (spline->points_deform == NULL || allocated_points != spline->tot_point) {
1787                 // printf("alloc new deform spline\n");
1788
1789                 if (spline->points_deform) {
1790                         int i;
1791
1792                         for (i = 0; i < allocated_points; i++) {
1793                                 MaskSplinePoint *point = &spline->points_deform[i];
1794                                 BKE_mask_point_free(point);
1795                         }
1796
1797                         MEM_freeN(spline->points_deform);
1798                 }
1799
1800                 spline->points_deform = MEM_callocN(sizeof(*spline->points_deform) * spline->tot_point, __func__);
1801         }
1802         else {
1803                 // printf("alloc spline done\n");
1804         }
1805 }
1806
1807 void BKE_mask_layer_evaluate(MaskLayer *masklay, const float ctime, const int do_newframe)
1808 {
1809         /* animation if available */
1810         if (do_newframe) {
1811                 MaskLayerShape *masklay_shape_a;
1812                 MaskLayerShape *masklay_shape_b;
1813                 int found;
1814
1815                 if ((found = BKE_mask_layer_shape_find_frame_range(masklay, ctime,
1816                                                                    &masklay_shape_a, &masklay_shape_b)))
1817                 {
1818                         if (found == 1) {
1819 #if 0
1820                                 printf("%s: exact %d %d (%d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1821                                        masklay_shape_a->frame);
1822 #endif
1823
1824                                 BKE_mask_layer_shape_to_mask(masklay, masklay_shape_a);
1825                         }
1826                         else if (found == 2) {
1827                                 float w = masklay_shape_b->frame - masklay_shape_a->frame;
1828 #if 0
1829                                 printf("%s: tween %d %d (%d %d)\n", __func__, (int)ctime, BLI_countlist(&masklay->splines_shapes),
1830                                        masklay_shape_a->frame, masklay_shape_b->frame);
1831 #endif
1832                                 BKE_mask_layer_shape_to_mask_interp(masklay, masklay_shape_a, masklay_shape_b,
1833                                                                     (ctime - masklay_shape_a->frame) / w);
1834                         }
1835                         else {
1836                                 /* always fail, should never happen */
1837                                 BLI_assert(found == 2);
1838                         }
1839                 }
1840         }
1841         /* animation done... */
1842
1843         BKE_mask_layer_calc_handles(masklay);
1844
1845         /* update deform */
1846         {
1847                 MaskSpline *spline;
1848
1849                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1850                         int i;
1851                         int has_auto = FALSE;
1852
1853                         BKE_mask_spline_ensure_deform(spline);
1854
1855                         for (i = 0; i < spline->tot_point; i++) {
1856                                 MaskSplinePoint *point = &spline->points[i];
1857                                 MaskSplinePoint *point_deform = &spline->points_deform[i];
1858                                 float delta[2];
1859
1860                                 BKE_mask_point_free(point_deform);
1861
1862                                 *point_deform = *point;
1863                                 point_deform->uw = point->uw ? MEM_dupallocN(point->uw) : NULL;
1864
1865                                 if (BKE_mask_evaluate_parent_delta(&point->parent, ctime, delta)) {
1866                                         add_v2_v2(point_deform->bezt.vec[0], delta);
1867                                         add_v2_v2(point_deform->bezt.vec[1], delta);
1868                                         add_v2_v2(point_deform->bezt.vec[2], delta);
1869                                 }
1870
1871                                 if (point->bezt.h1 == HD_AUTO) {
1872                                         has_auto = TRUE;
1873                                 }
1874                         }
1875
1876                         /* if the spline has auto handles, these need to be recalculated after deformation */
1877                         if (has_auto) {
1878                                 for (i = 0; i < spline->tot_point; i++) {
1879                                         MaskSplinePoint *point_deform = &spline->points_deform[i];
1880                                         if (point_deform->bezt.h1 == HD_AUTO) {
1881                                                 BKE_mask_calc_handle_point(spline, point_deform);
1882                                         }
1883                                 }
1884                         }
1885                         /* end extra calc handles loop */
1886                 }
1887         }
1888 }
1889
1890 void BKE_mask_evaluate(Mask *mask, const float ctime, const int do_newframe)
1891 {
1892         MaskLayer *masklay;
1893
1894         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1895                 BKE_mask_layer_evaluate(masklay, ctime, do_newframe);
1896         }
1897 }
1898
1899 /* the purpose of this function is to ensure spline->points_deform is never out of date.
1900  * for now re-evaluate all. eventually this might work differently */
1901 void BKE_mask_update_display(Mask *mask, float ctime)
1902 {
1903 #if 0
1904         MaskLayer *masklay;
1905
1906         for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
1907                 MaskSpline *spline;
1908
1909                 for (spline = masklay->splines.first; spline; spline = spline->next) {
1910                         if (spline->points_deform) {
1911                                 int i = 0;
1912
1913                                 for (i = 0; i < spline->tot_point; i++) {
1914                                         MaskSplinePoint *point;
1915
1916                                         if (spline->points_deform) {
1917                                                 point = &spline->points_deform[i];
1918                                                 BKE_mask_point_free(point);
1919                                         }
1920                                 }
1921                                 if (spline->points_deform) {
1922                                         MEM_freeN(spline->points_deform);
1923                                 }
1924
1925                                 spline->points_deform = NULL;
1926                         }
1927                 }
1928         }
1929 #endif
1930
1931         BKE_mask_evaluate(mask, ctime, FALSE);
1932 }
1933
1934 void BKE_mask_evaluate_all_masks(Main *bmain, float ctime, const int do_newframe)
1935 {
1936         Mask *mask;
1937
1938         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1939                 BKE_mask_evaluate(mask, ctime, do_newframe);
1940         }
1941 }
1942
1943 void BKE_mask_update_scene(Main *bmain, Scene *scene, const int do_newframe)
1944 {
1945         Mask *mask;
1946
1947         for (mask = bmain->mask.first; mask; mask = mask->id.next) {
1948                 if (mask->id.flag & LIB_ID_RECALC) {
1949                         BKE_mask_evaluate_all_masks(bmain, CFRA, do_newframe);
1950                 }
1951         }
1952 }
1953
1954 void BKE_mask_parent_init(MaskParent *parent)
1955 {
1956         parent->id_type = ID_MC;
1957 }
1958
1959
1960 /* *** own animation/shapekey implimentation ***
1961  * BKE_mask_layer_shape_XXX */
1962
1963 int BKE_mask_layer_shape_totvert(MaskLayer *masklay)
1964 {
1965         int tot = 0;
1966         MaskSpline *spline;
1967
1968         for (spline = masklay->splines.first; spline; spline = spline->next) {
1969                 tot += spline->tot_point;
1970         }
1971
1972         return tot;
1973 }
1974
1975 static void mask_layer_shape_from_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1976 {
1977         copy_v2_v2(&fp[0], bezt->vec[0]);
1978         copy_v2_v2(&fp[2], bezt->vec[1]);
1979         copy_v2_v2(&fp[4], bezt->vec[2]);
1980         fp[6] = bezt->weight;
1981         fp[7] = bezt->radius;
1982 }
1983
1984 static void mask_layer_shape_to_mask_point(BezTriple *bezt, float fp[MASK_OBJECT_SHAPE_ELEM_SIZE])
1985 {
1986         copy_v2_v2(bezt->vec[0], &fp[0]);
1987         copy_v2_v2(bezt->vec[1], &fp[2]);
1988         copy_v2_v2(bezt->vec[2], &fp[4]);
1989         bezt->weight = fp[6];
1990         bezt->radius = fp[7];
1991 }
1992
1993 /* these functions match. copy is swapped */
1994 void BKE_mask_layer_shape_from_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
1995 {
1996         int tot = BKE_mask_layer_shape_totvert(masklay);
1997
1998         if (masklay_shape->tot_vert == tot) {
1999                 float *fp = masklay_shape->data;
2000
2001                 MaskSpline *spline;
2002                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2003                         int i;
2004                         for (i = 0; i < spline->tot_point; i++) {
2005                                 mask_layer_shape_from_mask_point(&spline->points[i].bezt, fp);
2006                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
2007                         }
2008                 }
2009         }
2010         else {
2011                 printf("%s: vert mismatch %d != %d (frame %d)\n",
2012                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
2013         }
2014 }
2015
2016 void BKE_mask_layer_shape_to_mask(MaskLayer *masklay, MaskLayerShape *masklay_shape)
2017 {
2018         int tot = BKE_mask_layer_shape_totvert(masklay);
2019
2020         if (masklay_shape->tot_vert == tot) {
2021                 float *fp = masklay_shape->data;
2022
2023                 MaskSpline *spline;
2024                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2025                         int i;
2026                         for (i = 0; i < spline->tot_point; i++) {
2027                                 mask_layer_shape_to_mask_point(&spline->points[i].bezt, fp);
2028                                 fp += MASK_OBJECT_SHAPE_ELEM_SIZE;
2029                         }
2030                 }
2031         }
2032         else {
2033                 printf("%s: vert mismatch %d != %d (frame %d)\n",
2034                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
2035         }
2036 }
2037
2038 BLI_INLINE void interp_v2_v2v2_flfl(float target[2], const float a[2], const float b[2],
2039                                     const float t, const float s)
2040 {
2041         target[0] = s * a[0] + t * b[0];
2042         target[1] = s * a[1] + t * b[1];
2043 }
2044
2045 /* linear interpolation only */
2046 void BKE_mask_layer_shape_to_mask_interp(MaskLayer *masklay,
2047                                          MaskLayerShape *masklay_shape_a,
2048                                          MaskLayerShape *masklay_shape_b,
2049                                          const float fac)
2050 {
2051         int tot = BKE_mask_layer_shape_totvert(masklay);
2052         if (masklay_shape_a->tot_vert == tot && masklay_shape_b->tot_vert == tot) {
2053                 float *fp_a = masklay_shape_a->data;
2054                 float *fp_b = masklay_shape_b->data;
2055                 const float ifac = 1.0f - fac;
2056
2057                 MaskSpline *spline;
2058                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2059                         int i;
2060                         for (i = 0; i < spline->tot_point; i++) {
2061                                 BezTriple *bezt = &spline->points[i].bezt;
2062                                 /* *** BKE_mask_layer_shape_from_mask - swapped *** */
2063                                 interp_v2_v2v2_flfl(bezt->vec[0], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
2064                                 interp_v2_v2v2_flfl(bezt->vec[1], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
2065                                 interp_v2_v2v2_flfl(bezt->vec[2], fp_a, fp_b, fac, ifac); fp_a += 2; fp_b += 2;
2066                                 bezt->weight = (fp_a[0] * ifac) + (fp_b[0] * fac);
2067                                 bezt->radius = (fp_a[1] * ifac) + (fp_b[1] * fac); fp_a += 2; fp_b += 2;
2068                         }
2069                 }
2070         }
2071         else {
2072                 printf("%s: vert mismatch %d != %d != %d (frame %d - %d)\n",
2073                        __func__, masklay_shape_a->tot_vert, masklay_shape_b->tot_vert, tot,
2074                        masklay_shape_a->frame, masklay_shape_b->frame);
2075         }
2076 }
2077
2078 MaskLayerShape *BKE_mask_layer_shape_find_frame(MaskLayer *masklay, const int frame)
2079 {
2080         MaskLayerShape *masklay_shape;
2081
2082         for (masklay_shape = masklay->splines_shapes.first;
2083              masklay_shape;
2084              masklay_shape = masklay_shape->next)
2085         {
2086                 if (frame == masklay_shape->frame) {
2087                         return masklay_shape;
2088                 }
2089                 else if (frame < masklay_shape->frame) {
2090                         break;
2091                 }
2092         }
2093
2094         return NULL;
2095 }
2096
2097 /* when returning 2 - the frame isnt found but before/after frames are */
2098 int BKE_mask_layer_shape_find_frame_range(MaskLayer *masklay, const float frame,
2099                                           MaskLayerShape **r_masklay_shape_a,
2100                                           MaskLayerShape **r_masklay_shape_b)
2101 {
2102         MaskLayerShape *masklay_shape;
2103
2104         for (masklay_shape = masklay->splines_shapes.first;
2105              masklay_shape;
2106              masklay_shape = masklay_shape->next)
2107         {
2108                 if (frame == masklay_shape->frame) {
2109                         *r_masklay_shape_a = masklay_shape;
2110                         *r_masklay_shape_b = NULL;
2111                         return 1;
2112                 }
2113                 else if (frame < masklay_shape->frame) {
2114                         if (masklay_shape->prev) {
2115                                 *r_masklay_shape_a = masklay_shape->prev;
2116                                 *r_masklay_shape_b = masklay_shape;
2117                                 return 2;
2118                         }
2119                         else {
2120                                 *r_masklay_shape_a = masklay_shape;
2121                                 *r_masklay_shape_b = NULL;
2122                                 return 1;
2123                         }
2124                 }
2125         }
2126
2127         if ((masklay_shape = masklay->splines_shapes.last)) {
2128                 *r_masklay_shape_a = masklay_shape;
2129                 *r_masklay_shape_b = NULL;
2130                 return 1;
2131         }
2132         else {
2133                 *r_masklay_shape_a = NULL;
2134                 *r_masklay_shape_b = NULL;
2135
2136                 return 0;
2137         }
2138 }
2139
2140 MaskLayerShape *BKE_mask_layer_shape_varify_frame(MaskLayer *masklay, const int frame)
2141 {
2142         MaskLayerShape *masklay_shape;
2143
2144         masklay_shape = BKE_mask_layer_shape_find_frame(masklay, frame);
2145
2146         if (masklay_shape == NULL) {
2147                 masklay_shape = BKE_mask_layer_shape_alloc(masklay, frame);
2148                 BLI_addtail(&masklay->splines_shapes, masklay_shape);
2149                 BKE_mask_layer_shape_sort(masklay);
2150         }
2151
2152 #if 0
2153         {
2154                 MaskLayerShape *masklay_shape;
2155                 int i = 0;
2156                 for (masklay_shape = masklay->splines_shapes.first;
2157                      masklay_shape;
2158                      masklay_shape = masklay_shape->next)
2159                 {
2160                         printf("mask %d, %d\n", i++, masklay_shape->frame);
2161                 }
2162         }
2163 #endif
2164
2165         return masklay_shape;
2166 }
2167
2168 MaskLayerShape *BKE_mask_layer_shape_duplicate(MaskLayerShape *masklay_shape)
2169 {
2170         MaskLayerShape *masklay_shape_copy;
2171
2172         masklay_shape_copy = MEM_dupallocN(masklay_shape);
2173
2174         if (LIKELY(masklay_shape_copy->data)) {
2175                 masklay_shape_copy->data = MEM_dupallocN(masklay_shape_copy->data);
2176         }
2177
2178         return masklay_shape_copy;
2179 }
2180
2181 void BKE_mask_layer_shape_unlink(MaskLayer *masklay, MaskLayerShape *masklay_shape)
2182 {
2183         BLI_remlink(&masklay->splines_shapes, masklay_shape);
2184
2185         BKE_mask_layer_shape_free(masklay_shape);
2186 }
2187
2188 static int mask_layer_shape_sort_cb(void *masklay_shape_a_ptr, void *masklay_shape_b_ptr)
2189 {
2190         MaskLayerShape *masklay_shape_a = (MaskLayerShape *)masklay_shape_a_ptr;
2191         MaskLayerShape *masklay_shape_b = (MaskLayerShape *)masklay_shape_b_ptr;
2192
2193         if      (masklay_shape_a->frame < masklay_shape_b->frame)  return -1;
2194         else if (masklay_shape_a->frame > masklay_shape_b->frame)  return  1;
2195         else                                                       return  0;
2196 }
2197
2198 void BKE_mask_layer_shape_sort(MaskLayer *masklay)
2199 {
2200         BLI_sortlist(&masklay->splines_shapes, mask_layer_shape_sort_cb);
2201 }
2202
2203 int BKE_mask_layer_shape_spline_from_index(MaskLayer *masklay, int index,
2204                                            MaskSpline **r_masklay_shape, int *r_index)
2205 {
2206         MaskSpline *spline;
2207
2208         for (spline = masklay->splines.first; spline; spline = spline->next) {
2209                 if (index < spline->tot_point) {
2210                         *r_masklay_shape = spline;
2211                         *r_index = index;
2212                         return TRUE;
2213                 }
2214                 index -= spline->tot_point;
2215         }
2216
2217         return FALSE;
2218 }
2219
2220 int BKE_mask_layer_shape_spline_to_index(MaskLayer *masklay, MaskSpline *spline)
2221 {
2222         MaskSpline *spline_iter;
2223         int i_abs = 0;
2224         for (spline_iter = masklay->splines.first;
2225              spline_iter && spline_iter != spline;
2226              i_abs += spline_iter->tot_point, spline_iter = spline_iter->next)
2227         {
2228                 /* pass */
2229         }
2230
2231         return i_abs;
2232 }
2233
2234 /* basic 2D interpolation functions, could make more comprehensive later */
2235 static void interp_weights_uv_v2_calc(float r_uv[2], const float pt[2], const float pt_a[2], const float pt_b[2])
2236 {
2237         float pt_on_line[2];
2238         r_uv[0] = closest_to_line_v2(pt_on_line, pt, pt_a, pt_b);
2239         r_uv[1] = (len_v2v2(pt_on_line, pt) / len_v2v2(pt_a, pt_b)) *
2240                   ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0 : 1.0);  /* this line only sets the sign */
2241 }
2242
2243
2244 static void interp_weights_uv_v2_apply(const float uv[2], float r_pt[2], const float pt_a[2], const float pt_b[2])
2245 {
2246         const float dvec[2] = {pt_b[0] - pt_a[0],
2247                                pt_b[1] - pt_a[1]};
2248
2249         /* u */
2250         madd_v2_v2v2fl(r_pt, pt_a, dvec, uv[0]);
2251
2252         /* v */
2253         r_pt[0] += -dvec[1] * uv[1];
2254         r_pt[1] +=  dvec[0] * uv[1];
2255 }
2256
2257 /* when a now points added - resize all shapekey array  */
2258 void BKE_mask_layer_shape_changed_add(MaskLayer *masklay, int index,
2259                                       int do_init, int do_init_interpolate)
2260 {
2261         MaskLayerShape *masklay_shape;
2262
2263         /* spline index from masklay */
2264         MaskSpline *spline;
2265         int spline_point_index;
2266
2267         if (BKE_mask_layer_shape_spline_from_index(masklay, index,
2268                                                    &spline, &spline_point_index))
2269         {
2270                 /* sanity check */
2271                 /* the point has already been removed in this array so subtract one when comparing with the shapes */
2272                 int tot = BKE_mask_layer_shape_totvert(masklay) - 1;
2273
2274                 /* for interpolation */
2275                 /* TODO - assumes closed curve for now */
2276                 float uv[3][2]; /* 3x 2D handles */
2277                 const int pi_curr =   spline_point_index;
2278                 const int pi_prev = ((spline_point_index - 1) + spline->tot_point) % spline->tot_point;
2279                 const int pi_next =  (spline_point_index + 1)                      % spline->tot_point;
2280
2281                 const int index_offset = index - spline_point_index;
2282                 /* const int pi_curr_abs = index; */
2283                 const int pi_prev_abs = pi_prev + index_offset;
2284                 const int pi_next_abs = pi_next + index_offset;
2285
2286                 int i;
2287                 if (do_init_interpolate) {
2288                         for (i = 0; i < 3; i++) {
2289                                 interp_weights_uv_v2_calc(uv[i],
2290                                                           spline->points[pi_curr].bezt.vec[i],
2291                                                           spline->points[pi_prev].bezt.vec[i],
2292                                                           spline->points[pi_next].bezt.vec[i]);
2293                         }
2294                 }
2295
2296                 for (masklay_shape = masklay->splines_shapes.first;
2297                      masklay_shape;
2298                      masklay_shape = masklay_shape->next)
2299                 {
2300                         if (tot == masklay_shape->tot_vert) {
2301                                 float *data_resized;
2302
2303                                 masklay_shape->tot_vert++;
2304                                 data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
2305                                 if (index > 0) {
2306                                         memcpy(data_resized,
2307                                                masklay_shape->data,
2308                                                index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2309                                 }
2310
2311                                 if (index != masklay_shape->tot_vert - 1) {
2312                                         memcpy(&data_resized[(index + 1) * MASK_OBJECT_SHAPE_ELEM_SIZE],
2313                                                masklay_shape->data + (index * MASK_OBJECT_SHAPE_ELEM_SIZE),
2314                                                (masklay_shape->tot_vert - (index + 1)) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2315                                 }
2316
2317                                 if (do_init) {
2318                                         float *fp = &data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE];
2319
2320                                         mask_layer_shape_from_mask_point(&spline->points[spline_point_index].bezt, fp);
2321
2322                                         if (do_init_interpolate && spline->tot_point > 2) {
2323                                                 for (i = 0; i < 3; i++) {
2324                                                         interp_weights_uv_v2_apply(uv[i],
2325                                                                                    &fp[i * 2],
2326                                                                                    &data_resized[(pi_prev_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)],
2327                                                                                    &data_resized[(pi_next_abs * MASK_OBJECT_SHAPE_ELEM_SIZE) + (i * 2)]);
2328                                                 }
2329                                         }
2330                                 }
2331                                 else {
2332                                         memset(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
2333                                                0,
2334                                                sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2335                                 }
2336
2337                                 MEM_freeN(masklay_shape->data);
2338                                 masklay_shape->data = data_resized;
2339                         }
2340                         else {
2341                                 printf("%s: vert mismatch %d != %d (frame %d)\n",
2342                                        __func__, masklay_shape->tot_vert, tot, masklay_shape->frame);
2343                         }
2344                 }
2345         }
2346 }
2347
2348
2349 /* move array to account for removed point */
2350 void BKE_mask_layer_shape_changed_remove(MaskLayer *masklay, int index, int count)
2351 {
2352         MaskLayerShape *masklay_shape;
2353
2354         /* the point has already been removed in this array so add one when comparing with the shapes */
2355         int tot = BKE_mask_layer_shape_totvert(masklay);
2356
2357         for (masklay_shape = masklay->splines_shapes.first;
2358              masklay_shape;
2359              masklay_shape = masklay_shape->next)
2360         {
2361                 if (tot == masklay_shape->tot_vert - count) {
2362                         float *data_resized;
2363
2364                         masklay_shape->tot_vert -= count;
2365                         data_resized = MEM_mallocN(masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE, __func__);
2366                         if (index > 0) {
2367                                 memcpy(data_resized,
2368                                        masklay_shape->data,
2369                                        index * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2370                         }
2371
2372                         if (index != masklay_shape->tot_vert) {
2373                                 memcpy(&data_resized[index * MASK_OBJECT_SHAPE_ELEM_SIZE],
2374                                        masklay_shape->data + ((index + count) * MASK_OBJECT_SHAPE_ELEM_SIZE),
2375                                        (masklay_shape->tot_vert - index) * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE);
2376                         }
2377
2378                         MEM_freeN(masklay_shape->data);
2379                         masklay_shape->data = data_resized;
2380                 }
2381                 else {
2382                         printf("%s: vert mismatch %d != %d (frame %d)\n",
2383                                __func__, masklay_shape->tot_vert - count, tot, masklay_shape->frame);
2384                 }
2385         }
2386 }
2387
2388 /* local functions */
2389 static void invert_vn_vn(float *array, const int size)
2390 {
2391         float *arr = array + (size - 1);
2392         int i = size;
2393         while (i--) {
2394                 *(arr) = 1.0f - *(arr);
2395                 arr--;
2396         }
2397 }
2398
2399 static void m_invert_vn_vn(float *array, const float f, const int size)
2400 {
2401         float *arr = array + (size - 1);
2402         int i = size;
2403         while (i--) {
2404                 *(arr) = 1.0f - (*(arr) * f);
2405                 arr--;
2406         }
2407 }
2408
2409 static void clamp_vn_vn(float *array, const int size)
2410 {
2411         float *arr = array + (size - 1);
2412
2413         int i = size;
2414         while (i--) {
2415                 if      (*arr < 0.0f) *arr = 0.0f;
2416                 else if (*arr > 1.0f) *arr = 1.0f;
2417                 arr--;
2418         }
2419 }
2420
2421 int BKE_mask_get_duration(Mask *mask)
2422 {
2423         return MAX2(1, mask->efra - mask->sfra);
2424 }
2425
2426 #ifdef USE_MANGO_MASK_CACHE_HACK
2427 static int mask_point_compare(MaskSplinePoint *point_a, MaskSplinePoint *point_b)
2428 {
2429         if (point_a->tot_uw != point_b->tot_uw) {
2430                 return FALSE;
2431         }
2432
2433         if (memcmp(&point_a->bezt, &point_b->bezt, sizeof(BezTriple))) {
2434                 return FALSE;
2435         }
2436
2437         if (memcmp(&point_a->uw, &point_b->uw, 2 * point_a->tot_uw * sizeof(float))) {
2438                 return FALSE;
2439         }
2440
2441         return TRUE;
2442 }
2443
2444 static int mask_points_compare(MaskSplinePoint *points_a, MaskSplinePoint *points_b, int tot_point)
2445 {
2446         MaskSplinePoint *point_a = points_a;
2447         MaskSplinePoint *point_b = points_b;
2448         int a = tot_point;
2449
2450         /* deform points can be NULL */
2451         if (point_a == NULL || point_b == NULL) {
2452                 return ((point_a == NULL) && (point_b == NULL));
2453         }
2454
2455         while (a--) {
2456                 if (!mask_point_compare(point_a, point_b)) {
2457                         return FALSE;
2458                 }
2459
2460                 point_a++;
2461                 point_b++;
2462         }
2463
2464         return TRUE;
2465 }
2466
2467 static int mask_spline_compare(MaskSpline *spline_a, MaskSpline *spline_b)
2468 {
2469         if (spline_a->flag != spline_b->flag ||
2470             spline_a->tot_point != spline_b->tot_point ||
2471             spline_a->weight_interp != spline_b->weight_interp)
2472         {
2473                 return FALSE;
2474         }
2475
2476         if (!mask_points_compare(spline_a->points, spline_b->points, spline_a->tot_point)) {
2477                 return FALSE;
2478         }
2479
2480         return mask_points_compare(spline_a->points_deform, spline_b->points_deform, spline_a->tot_point);
2481 }
2482
2483 static int mask_splines_compare(ListBase *base_a, ListBase *base_b)
2484 {
2485         MaskSpline *spline_a, *spline_b;
2486
2487         for (spline_a = base_a->first, spline_b = base_b->first;
2488              spline_a && spline_b;
2489              spline_a = spline_a->next, spline_b = spline_b->next)
2490         {
2491                 if (!mask_spline_compare(spline_a, spline_b)) {
2492                         return FALSE;
2493                 }
2494         }
2495
2496         if (spline_a || spline_b)
2497                 return FALSE;
2498
2499         return TRUE;
2500 }
2501
2502 static int mask_layer_compare(MaskLayer *layer_a, MaskLayer *layer_b)
2503 {
2504         if (layer_a->alpha != layer_b->alpha ||
2505             layer_a->blend != layer_b->blend ||
2506             layer_a->blend_flag != layer_b->blend_flag ||
2507             layer_a->flag != layer_b->flag ||
2508             layer_a->restrictflag != layer_b->restrictflag)
2509         {
2510                 return FALSE;
2511         }
2512
2513         if (strcmp(layer_a->name, layer_b->name))
2514                 return FALSE;
2515
2516         return mask_splines_compare(&layer_a->splines, &layer_b->splines);
2517 }
2518
2519 static int mask_layers_compare(ListBase *base_a, ListBase *base_b)
2520 {
2521         MaskLayer *layer_a, *layer_b;
2522
2523         for (layer_a = base_a->first, layer_b = base_b->first;
2524              layer_a && layer_b;
2525              layer_a = layer_a->next, layer_b = layer_b->next)
2526         {
2527                 if (!mask_layer_compare(layer_a, layer_b)) {
2528                         return FALSE;
2529                 }
2530         }
2531
2532         if (layer_a || layer_b)
2533                 return FALSE;
2534
2535         return TRUE;
2536 }
2537 #endif
2538
2539 /* rasterization */
2540
2541 /* XXX: mask is only passed here to access rasterization cache
2542  *      this MUST be removed as soon as tile-based rasterization would be here
2543  */
2544 void BKE_mask_rasterize_layers(Mask *mask, ListBase *masklayers, int width, int height, float *buffer,
2545                                const short do_aspect_correct, const short do_mask_aa,
2546                                const short do_feather)
2547 {
2548         MaskRasterCache *cache = mask->raster_cache;
2549         MaskLayer *masklay;
2550
2551         /* temp blending buffer */
2552         const int buffer_size = width * height;
2553         float *buffer_tmp;
2554
2555 #ifdef USE_MANGO_MASK_CACHE_HACK
2556         BLI_lock_thread(LOCK_CUSTOM1);
2557
2558         if (cache &&
2559             cache->width == width &&
2560             cache->height == height &&
2561             cache->do_aspect_correct == do_aspect_correct &&
2562             cache->do_mask_aa == do_mask_aa &&
2563             cache->do_feather == do_feather &&
2564             mask_layers_compare(&cache->layers, &mask->masklayers))
2565         {
2566                 memcpy(buffer, cache->buffer, sizeof(float) * buffer_size);
2567
2568                 BLI_unlock_thread(LOCK_CUSTOM1);
2569
2570                 return;
2571         }
2572
2573         BLI_unlock_thread(LOCK_CUSTOM1);
2574 #endif
2575
2576         buffer_tmp = MEM_mallocN(sizeof(float) * buffer_size, __func__);
2577
2578         for (masklay = masklayers->first; masklay; masklay = masklay->next) {
2579                 MaskSpline *spline;
2580                 float alpha;
2581
2582                 if (masklay->restrictflag & MASK_RESTRICT_RENDER) {
2583                         continue;
2584                 }
2585
2586                 memset(buffer_tmp, 0, sizeof(float) * buffer_size);
2587
2588                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2589                         float (*diff_points)[2];
2590                         int tot_diff_point;
2591
2592                         float (*diff_feather_points)[2];
2593                         int tot_diff_feather_points;
2594
2595                         diff_points = BKE_mask_spline_differentiate_with_resolution(spline, width, height,
2596                                                                                     &tot_diff_point);
2597
2598                         if (tot_diff_point) {
2599                                 if (do_feather) {
2600                                         diff_feather_points =
2601                                                 BKE_mask_spline_feather_differentiated_points_with_resolution(spline, width, height,
2602                                                                                                               &tot_diff_feather_points);
2603                                 }
2604                                 else {
2605                                         tot_diff_feather_points = 0;
2606                                         diff_feather_points = NULL;
2607                                 }
2608
2609                                 if (do_aspect_correct) {
2610                                         if (width != height) {
2611                                                 float *fp;
2612                                                 float *ffp;
2613                                                 int i;
2614                                                 float asp;
2615
2616                                                 if (width < height) {
2617                                                         fp = &diff_points[0][0];
2618                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][0] : NULL;
2619                                                         asp = (float)width / (float)height;
2620                                                 }
2621                                                 else {
2622                                                         fp = &diff_points[0][1];
2623                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][1] : NULL;
2624                                                         asp = (float)height / (float)width;
2625                                                 }
2626
2627                                                 for (i = 0; i < tot_diff_point; i++, fp += 2) {
2628                                                         (*fp) = (((*fp) - 0.5f) / asp) + 0.5f;
2629                                                 }
2630
2631                                                 if (tot_diff_feather_points) {
2632                                                         for (i = 0; i < tot_diff_feather_points; i++, ffp += 2) {
2633                                                                 (*ffp) = (((*ffp) - 0.5f) / asp) + 0.5f;
2634                                                         }
2635                                                 }
2636                                         }
2637                                 }
2638
2639                                 if (tot_diff_point) {
2640                                         PLX_raskterize(diff_points, tot_diff_point,
2641                                    buffer_tmp, width, height,do_mask_aa);
2642
2643                                         if (tot_diff_feather_points) {
2644                                                 PLX_raskterize_feather(diff_points, tot_diff_point,
2645                                                                        diff_feather_points, tot_diff_feather_points,
2646                                                                        buffer_tmp, width, height);
2647                                                 MEM_freeN(diff_feather_points);
2648                                         }
2649
2650                                         MEM_freeN(diff_points);
2651                                 }
2652                         }
2653                 }
2654
2655                 /* blend with original */
2656                 if (masklay->blend_flag & MASK_BLENDFLAG_INVERT) {
2657                         /* apply alpha multiply before inverting */
2658                         if (masklay->alpha != 1.0f) {
2659                                 m_invert_vn_vn(buffer_tmp, masklay->alpha, buffer_size);
2660                         }
2661                         else {
2662                                 invert_vn_vn(buffer_tmp, buffer_size);
2663                         }
2664
2665                         alpha = 1.0f;
2666                 }
2667                 else {
2668                         alpha = masklay->alpha;
2669                 }
2670
2671                 switch (masklay->blend) {
2672                         case MASK_BLEND_SUBTRACT:
2673                         {
2674                                 if (alpha == 1.0f) {
2675                                         sub_vn_vn(buffer, buffer_tmp, buffer_size);
2676                                 }
2677                                 else {
2678                                         msub_vn_vn(buffer, buffer_tmp, alpha, buffer_size);
2679                                 }
2680                                 break;
2681                         }
2682                         case MASK_BLEND_ADD:
2683                         default:
2684                         {
2685                                 if (alpha == 1.0f) {
2686                                         add_vn_vn(buffer, buffer_tmp, buffer_size);
2687                                 }
2688                                 else {
2689                                         madd_vn_vn(buffer, buffer_tmp, alpha, buffer_size);
2690                                 }
2691                                 break;
2692                         }
2693                 }
2694
2695                 if(do_mask_aa){
2696                         //PLX_antialias_buffer(buffer,width,height);
2697                 }
2698                 /* clamp at the end */
2699                 clamp_vn_vn(buffer, buffer_size);
2700         }
2701         MEM_freeN(buffer_tmp);
2702
2703 #ifdef USE_MANGO_MASK_CACHE_HACK
2704         BLI_lock_thread(LOCK_CUSTOM1);
2705
2706         BKE_mask_raster_cache_free(mask);
2707
2708         cache = MEM_callocN(sizeof(MaskRasterCache), "mask raster cache");
2709
2710         cache->buffer = MEM_mallocN(sizeof(float) * buffer_size, "mask raster cache buffer");
2711
2712         BKE_mask_layer_copy_list(&cache->layers, masklayers);
2713
2714         memcpy(cache->buffer, buffer, sizeof(float) * buffer_size);
2715
2716         cache->width = width;
2717         cache->height = height;
2718         cache->do_aspect_correct = do_aspect_correct;
2719         cache->do_mask_aa = do_mask_aa;
2720         cache->do_feather = do_feather;
2721
2722         mask->raster_cache = cache;
2723
2724         BLI_unlock_thread(LOCK_CUSTOM1);
2725 #endif
2726 }
2727
2728 #ifdef __PLX_RASKTER_MT__
2729 void BKE_mask_init_layers(Mask *mask, struct layer_init_data *mlayer_data, int width, int height, const short do_aspect_correct){
2730         MaskLayer *masklay;
2731         int numLayers=0;
2732         int currLayer=0;
2733         for (masklay = mask->masklayers->first; masklay; masklay = masklay->next) {
2734                 numLayers++;
2735         }
2736         mlayer_data = MEM_mallocN(sizeof(struct layer_init_data) * numLayers, __func__); //size correct?
2737         
2738         
2739         for (masklay = mask->masklayers->first; masklay; masklay = masklay->next) {
2740                 MaskSpline *spline;
2741                 for (spline = masklay->splines.first; spline; spline = spline->next) {
2742                         float (*diff_points)[2];
2743                         int tot_diff_point;
2744
2745                         float (*diff_feather_points)[2];
2746                         int tot_diff_feather_points;
2747
2748                         diff_points = BKE_mask_spline_differentiate_with_resolution(spline, width, height,
2749                                                                                     &tot_diff_point);
2750
2751                         if (tot_diff_point) {
2752                                 if (do_feather) {
2753                                         diff_feather_points =
2754                                                 BKE_mask_spline_feather_differentiated_points_with_resolution(spline, width, height,
2755                                                                                                               &tot_diff_feather_points);
2756                                 }
2757                                 else {
2758                                         tot_diff_feather_points = 0;
2759                                         diff_feather_points = NULL;
2760                                 }
2761
2762                                 if (do_aspect_correct) {
2763                                         if (width != height) {
2764                                                 float *fp;
2765                                                 float *ffp;
2766                                                 int i;
2767                                                 float asp;
2768
2769                                                 if (width < height) {
2770                                                         fp = &diff_points[0][0];
2771                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][0] : NULL;
2772                                                         asp = (float)width / (float)height;
2773                                                 }
2774                                                 else {
2775                                                         fp = &diff_points[0][1];
2776                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][1] : NULL;
2777                                                         asp = (float)height / (float)width;
2778                                                 }
2779
2780                                                 for (i = 0; i < tot_diff_point; i++, fp += 2) {
2781                                                         (*fp) = (((*fp) - 0.5f) / asp) + 0.5f;
2782                                                 }
2783
2784                                                 if (tot_diff_feather_points) {
2785                                                         for (i = 0; i < tot_diff_feather_points; i++, ffp += 2) {
2786                                                                 (*ffp) = (((*ffp) - 0.5f) / asp) + 0.5f;
2787                                                         }
2788                                                 }
2789                                         }
2790                                 }
2791                                 PLX_init_base_data(mlayer_data[currLayer], diff_points, tot_diff_points, width, height);
2792                                 currLayer++;
2793                         }
2794                 }
2795         }
2796 }
2797 #endif
2798
2799 void BKE_mask_rasterize(Mask *mask, int width, int height, float *buffer,
2800                         const short do_aspect_correct, const short do_mask_aa,
2801                         const short do_feather)
2802 {
2803         BKE_mask_rasterize_layers(mask, &mask->masklayers, width, height, buffer, do_aspect_correct, do_mask_aa, do_feather);
2804 }