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