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