Logging: Use CLOG for blenkernel
[blender.git] / source / blender / blenkernel / intern / mask_rasterize.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  *                 Campbell Barton
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenkernel/intern/mask_rasterize.c
28  *  \ingroup bke
29  *
30  * This module exposes a rasterizer that works as a black box - implementation details are confined to this file,
31  *
32  * The basic method to access is:
33  * - create & initialize a handle from a #Mask datablock.
34  * - execute pixel lookups.
35  * - free the handle.
36  *
37  * This file is admittedly a bit confusticated, in quite few areas speed was chosen over readability,
38  * though it is commented - so shouldn't be so hard to see what's going on.
39  *
40  *
41  * Implementation:
42  *
43  * To rasterize the mask its converted into geometry that use a ray-cast for each pixel lookup.
44  *
45  * Initially 'kdopbvh' was used but this ended up being too slow.
46  *
47  * To gain some extra speed we take advantage of a few shortcuts that can be made rasterizing masks specifically.
48  * - all triangles are known to be completely white - so no depth check is done on triangle intersection.
49  * - all quads are known to be feather outlines - the 1 and 0 depths are known by the vertex order in the quad,
50  * - there is no color - just a value for each mask pixel.
51  * - the mask spacial structure always maps to space 0-1 on X and Y axis.
52  * - bucketing is used to speed up lookups for geometry.
53  *
54  * Other Details:
55  * - used unsigned values all over for some extra speed on some arch's.
56  * - anti-aliasing is faked, just ensuring at least one pixel feather - avoids oversampling.
57  * - initializing the spacial structure doesn't need to be as optimized as pixel lookups are.
58  * - mask lookups need not be pixel aligned so any sub-pixel values from x/y (0 - 1), can be found.
59  *   (perhaps masks can be used as a vector texture in 3D later on)
60  *
61  *
62  * Currently, to build the spacial structure we have to calculate the total number of faces ahead of time.
63  *
64  * This is getting a bit complicated with the addition of unfilled splines and end capping -
65  * If large changes are needed here we would be better off using an iterable
66  * BLI_mempool for triangles and converting to a contiguous array afterwards.
67  *
68  * - Campbell
69  */
70
71 #include "CLG_log.h"
72
73 #include "MEM_guardedalloc.h"
74
75 #include "DNA_vec_types.h"
76 #include "DNA_mask_types.h"
77 #include "DNA_scene_types.h"
78
79 #include "BLI_utildefines.h"
80 #include "BLI_scanfill.h"
81 #include "BLI_memarena.h"
82
83 #include "BLI_math.h"
84 #include "BLI_rect.h"
85 #include "BLI_task.h"
86 #include "BLI_listbase.h"
87 #include "BLI_linklist.h"
88
89 #include "BKE_mask.h"
90
91 #include "BLI_strict_flags.h"
92
93 /* this is rather and annoying hack, use define to isolate it.
94  * problem is caused by scanfill removing edges on us. */
95 #define USE_SCANFILL_EDGE_WORKAROUND
96
97 #define SPLINE_RESOL_CAP_PER_PIXEL 2
98 #define SPLINE_RESOL_CAP_MIN 8
99 #define SPLINE_RESOL_CAP_MAX 64
100
101 /* found this gives best performance for high detail masks, values between 2 and 8 work best */
102 #define BUCKET_PIXELS_PER_CELL 4
103
104 #define SF_EDGE_IS_BOUNDARY 0xff
105 #define SF_KEYINDEX_TEMP_ID ((unsigned int) -1)
106
107 #define TRI_TERMINATOR_ID   ((unsigned int) -1)
108 #define TRI_VERT            ((unsigned int) -1)
109
110 /* for debugging add... */
111 #ifndef NDEBUG
112 /* printf("%u %u %u %u\n", _t[0], _t[1], _t[2], _t[3]); \ */
113 #  define FACE_ASSERT(face, vert_max)                    \
114 {                                                        \
115         unsigned int *_t = face;                             \
116         BLI_assert(_t[0] < vert_max);                        \
117         BLI_assert(_t[1] < vert_max);                        \
118         BLI_assert(_t[2] < vert_max);                        \
119         BLI_assert(_t[3] < vert_max || _t[3] == TRI_VERT);   \
120 } (void)0
121 #else
122    /* do nothing */
123 #  define FACE_ASSERT(face, vert_max)
124 #endif
125
126 static CLG_LogRef LOG = {"bke.mask_rasterize"};
127
128 static void rotate_point_v2(float r_p[2], const float p[2], const float cent[2], const float angle, const float asp[2])
129 {
130         const float s = sinf(angle);
131         const float c = cosf(angle);
132         float p_new[2];
133
134         /* translate point back to origin */
135         r_p[0] = (p[0] - cent[0]) / asp[0];
136         r_p[1] = (p[1] - cent[1]) / asp[1];
137
138         /* rotate point */
139         p_new[0] = ((r_p[0] * c) - (r_p[1] * s)) * asp[0];
140         p_new[1] = ((r_p[0] * s) + (r_p[1] * c)) * asp[1];
141
142         /* translate point back */
143         r_p[0] = p_new[0] + cent[0];
144         r_p[1] = p_new[1] + cent[1];
145 }
146
147 BLI_INLINE unsigned int clampis_uint(const unsigned int v, const unsigned int min, const unsigned int max)
148 {
149         return v < min ? min : (v > max ? max : v);
150 }
151
152 /* --------------------------------------------------------------------- */
153 /* local structs for mask rasterizeing                                   */
154 /* --------------------------------------------------------------------- */
155
156 /**
157  * A single #MaskRasterHandle contains multiple #MaskRasterLayer's,
158  * each #MaskRasterLayer does its own lookup which contributes to
159  * the final pixel with its own blending mode and the final pixel
160  * is blended between these.
161  */
162
163 /* internal use only */
164 typedef struct MaskRasterLayer {
165         /* geometry */
166         unsigned int   face_tot;
167         unsigned int (*face_array)[4];  /* access coords tri/quad */
168         float        (*face_coords)[3]; /* xy, z 0-1 (1.0 == filled) */
169
170
171         /* 2d bounds (to quickly skip bucket lookup) */
172         rctf bounds;
173
174
175         /* buckets */
176         unsigned int **buckets_face;
177         /* cache divide and subtract */
178         float buckets_xy_scalar[2]; /* (1.0 / (buckets_width + FLT_EPSILON)) * buckets_x */
179         unsigned int buckets_x;
180         unsigned int buckets_y;
181
182
183         /* copied direct from #MaskLayer.--- */
184         /* blending options */
185         float  alpha;
186         char   blend;
187         char   blend_flag;
188         char   falloff;
189
190 } MaskRasterLayer;
191
192 typedef struct MaskRasterSplineInfo {
193         /* body of the spline */
194         unsigned int vertex_offset;
195         unsigned int vertex_total;
196
197         /* capping for non-filled, non cyclic splines */
198         unsigned int vertex_total_cap_head;
199         unsigned int vertex_total_cap_tail;
200
201         bool is_cyclic;
202 } MaskRasterSplineInfo;
203
204 /**
205  * opaque local struct for mask pixel lookup, each MaskLayer needs one of these
206  */
207 struct MaskRasterHandle {
208         MaskRasterLayer *layers;
209         unsigned int     layers_tot;
210
211         /* 2d bounds (to quickly skip bucket lookup) */
212         rctf bounds;
213 };
214
215 /* --------------------------------------------------------------------- */
216 /* alloc / free functions                                                */
217 /* --------------------------------------------------------------------- */
218
219 MaskRasterHandle *BKE_maskrasterize_handle_new(void)
220 {
221         MaskRasterHandle *mr_handle;
222
223         mr_handle = MEM_callocN(sizeof(MaskRasterHandle), "MaskRasterHandle");
224
225         return mr_handle;
226 }
227
228 void BKE_maskrasterize_handle_free(MaskRasterHandle *mr_handle)
229 {
230         const unsigned int layers_tot = mr_handle->layers_tot;
231         unsigned int i;
232         MaskRasterLayer *layer = mr_handle->layers;
233
234         for (i = 0; i < layers_tot; i++, layer++) {
235
236                 if (layer->face_array) {
237                         MEM_freeN(layer->face_array);
238                 }
239
240                 if (layer->face_coords) {
241                         MEM_freeN(layer->face_coords);
242                 }
243
244                 if (layer->buckets_face) {
245                         const unsigned int   bucket_tot = layer->buckets_x * layer->buckets_y;
246                         unsigned int bucket_index;
247                         for (bucket_index = 0; bucket_index < bucket_tot; bucket_index++) {
248                                 unsigned int *face_index = layer->buckets_face[bucket_index];
249                                 if (face_index) {
250                                         MEM_freeN(face_index);
251                                 }
252                         }
253
254                         MEM_freeN(layer->buckets_face);
255                 }
256         }
257
258         MEM_freeN(mr_handle->layers);
259         MEM_freeN(mr_handle);
260 }
261
262
263 static void maskrasterize_spline_differentiate_point_outset(float (*diff_feather_points)[2], float (*diff_points)[2],
264                                                             const unsigned int tot_diff_point, const float ofs,
265                                                             const bool do_test)
266 {
267         unsigned int k_prev = tot_diff_point - 2;
268         unsigned int k_curr = tot_diff_point - 1;
269         unsigned int k_next = 0;
270
271         unsigned int k;
272
273         float d_prev[2];
274         float d_next[2];
275         float d[2];
276
277         const float *co_prev;
278         const float *co_curr;
279         const float *co_next;
280
281         const float ofs_squared = ofs * ofs;
282
283         co_prev = diff_points[k_prev];
284         co_curr = diff_points[k_curr];
285         co_next = diff_points[k_next];
286
287         /* precalc */
288         sub_v2_v2v2(d_prev, co_prev, co_curr);
289         normalize_v2(d_prev);
290
291         for (k = 0; k < tot_diff_point; k++) {
292
293                 /* co_prev = diff_points[k_prev]; */ /* precalc */
294                 co_curr = diff_points[k_curr];
295                 co_next = diff_points[k_next];
296
297                 /* sub_v2_v2v2(d_prev, co_prev, co_curr); */ /* precalc */
298                 sub_v2_v2v2(d_next, co_curr, co_next);
299
300                 /* normalize_v2(d_prev); */ /* precalc */
301                 normalize_v2(d_next);
302
303                 if ((do_test == false) ||
304                     (len_squared_v2v2(diff_feather_points[k], diff_points[k]) < ofs_squared))
305                 {
306
307                         add_v2_v2v2(d, d_prev, d_next);
308
309                         normalize_v2(d);
310
311                         diff_feather_points[k][0] = diff_points[k][0] + ( d[1] * ofs);
312                         diff_feather_points[k][1] = diff_points[k][1] + (-d[0] * ofs);
313                 }
314
315                 /* use next iter */
316                 copy_v2_v2(d_prev, d_next);
317
318                 /* k_prev = k_curr; */ /* precalc */
319                 k_curr = k_next;
320                 k_next++;
321         }
322 }
323
324 /* this function is not exact, sometimes it returns false positives,
325  * the main point of it is to clear out _almost_ all bucket/face non-intersections,
326  * returning true in corner cases is ok but missing an intersection is NOT.
327  *
328  * method used
329  * - check if the center of the buckets bounding box is intersecting the face
330  * - if not get the max radius to a corner of the bucket and see how close we
331  *   are to any of the triangle edges.
332  */
333 static bool layer_bucket_isect_test(
334         const MaskRasterLayer *layer, unsigned int face_index,
335         const unsigned int bucket_x, const unsigned int bucket_y,
336         const float bucket_size_x, const float bucket_size_y,
337         const float bucket_max_rad_squared)
338 {
339         unsigned int *face = layer->face_array[face_index];
340         float (*cos)[3] = layer->face_coords;
341
342         const float xmin = layer->bounds.xmin + (bucket_size_x * (float)bucket_x);
343         const float ymin = layer->bounds.ymin + (bucket_size_y * (float)bucket_y);
344         const float xmax = xmin + bucket_size_x;
345         const float ymax = ymin + bucket_size_y;
346
347         const float cent[2] = {(xmin + xmax) * 0.5f,
348                                (ymin + ymax) * 0.5f};
349
350         if (face[3] == TRI_VERT) {
351                 const float *v1 = cos[face[0]];
352                 const float *v2 = cos[face[1]];
353                 const float *v3 = cos[face[2]];
354
355                 if (isect_point_tri_v2(cent, v1, v2, v3)) {
356                         return true;
357                 }
358                 else {
359                         if ((dist_squared_to_line_segment_v2(cent, v1, v2) < bucket_max_rad_squared) ||
360                             (dist_squared_to_line_segment_v2(cent, v2, v3) < bucket_max_rad_squared) ||
361                             (dist_squared_to_line_segment_v2(cent, v3, v1) < bucket_max_rad_squared))
362                         {
363                                 return true;
364                         }
365                         else {
366                                 // printf("skip tri\n");
367                                 return false;
368                         }
369                 }
370
371         }
372         else {
373                 const float *v1 = cos[face[0]];
374                 const float *v2 = cos[face[1]];
375                 const float *v3 = cos[face[2]];
376                 const float *v4 = cos[face[3]];
377
378                 if (isect_point_tri_v2(cent, v1, v2, v3)) {
379                         return true;
380                 }
381                 else if (isect_point_tri_v2(cent, v1, v3, v4)) {
382                         return true;
383                 }
384                 else {
385                         if ((dist_squared_to_line_segment_v2(cent, v1, v2) < bucket_max_rad_squared) ||
386                             (dist_squared_to_line_segment_v2(cent, v2, v3) < bucket_max_rad_squared) ||
387                             (dist_squared_to_line_segment_v2(cent, v3, v4) < bucket_max_rad_squared) ||
388                             (dist_squared_to_line_segment_v2(cent, v4, v1) < bucket_max_rad_squared))
389                         {
390                                 return true;
391                         }
392                         else {
393                                 // printf("skip quad\n");
394                                 return false;
395                         }
396                 }
397         }
398 }
399
400 static void layer_bucket_init_dummy(MaskRasterLayer *layer)
401 {
402         layer->face_tot = 0;
403         layer->face_coords = NULL;
404         layer->face_array  = NULL;
405
406         layer->buckets_x = 0;
407         layer->buckets_y = 0;
408
409         layer->buckets_xy_scalar[0] = 0.0f;
410         layer->buckets_xy_scalar[1] = 0.0f;
411
412         layer->buckets_face = NULL;
413
414         BLI_rctf_init(&layer->bounds, -1.0f, -1.0f, -1.0f, -1.0f);
415 }
416
417 static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size)
418 {
419         MemArena *arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 16), __func__);
420
421         const float bucket_dim_x = BLI_rctf_size_x(&layer->bounds);
422         const float bucket_dim_y = BLI_rctf_size_y(&layer->bounds);
423
424         layer->buckets_x = (unsigned int)((bucket_dim_x / pixel_size) / (float)BUCKET_PIXELS_PER_CELL);
425         layer->buckets_y = (unsigned int)((bucket_dim_y / pixel_size) / (float)BUCKET_PIXELS_PER_CELL);
426
427 //              printf("bucket size %ux%u\n", layer->buckets_x, layer->buckets_y);
428
429         CLAMP(layer->buckets_x, 8, 512);
430         CLAMP(layer->buckets_y, 8, 512);
431
432         layer->buckets_xy_scalar[0] = (1.0f / (bucket_dim_x + FLT_EPSILON)) * (float)layer->buckets_x;
433         layer->buckets_xy_scalar[1] = (1.0f / (bucket_dim_y + FLT_EPSILON)) * (float)layer->buckets_y;
434
435         {
436                 /* width and height of each bucket */
437                 const float bucket_size_x = (bucket_dim_x + FLT_EPSILON) / (float)layer->buckets_x;
438                 const float bucket_size_y = (bucket_dim_y + FLT_EPSILON) / (float)layer->buckets_y;
439                 const float bucket_max_rad = (max_ff(bucket_size_x, bucket_size_y) * (float)M_SQRT2) + FLT_EPSILON;
440                 const float bucket_max_rad_squared = bucket_max_rad * bucket_max_rad;
441
442                 unsigned int *face = &layer->face_array[0][0];
443                 float (*cos)[3] = layer->face_coords;
444
445                 const unsigned int  bucket_tot = layer->buckets_x * layer->buckets_y;
446                 LinkNode     **bucketstore     = MEM_callocN(bucket_tot * sizeof(LinkNode *),  __func__);
447                 unsigned int  *bucketstore_tot = MEM_callocN(bucket_tot * sizeof(unsigned int), __func__);
448
449                 unsigned int face_index;
450
451                 for (face_index = 0; face_index < layer->face_tot; face_index++, face += 4) {
452                         float xmin;
453                         float xmax;
454                         float ymin;
455                         float ymax;
456
457                         if (face[3] == TRI_VERT) {
458                                 const float *v1 = cos[face[0]];
459                                 const float *v2 = cos[face[1]];
460                                 const float *v3 = cos[face[2]];
461
462                                 xmin = min_ff(v1[0], min_ff(v2[0], v3[0]));
463                                 xmax = max_ff(v1[0], max_ff(v2[0], v3[0]));
464                                 ymin = min_ff(v1[1], min_ff(v2[1], v3[1]));
465                                 ymax = max_ff(v1[1], max_ff(v2[1], v3[1]));
466                         }
467                         else {
468                                 const float *v1 = cos[face[0]];
469                                 const float *v2 = cos[face[1]];
470                                 const float *v3 = cos[face[2]];
471                                 const float *v4 = cos[face[3]];
472
473                                 xmin = min_ff(v1[0], min_ff(v2[0], min_ff(v3[0], v4[0])));
474                                 xmax = max_ff(v1[0], max_ff(v2[0], max_ff(v3[0], v4[0])));
475                                 ymin = min_ff(v1[1], min_ff(v2[1], min_ff(v3[1], v4[1])));
476                                 ymax = max_ff(v1[1], max_ff(v2[1], max_ff(v3[1], v4[1])));
477                         }
478
479
480                         /* not essential but may as will skip any faces outside the view */
481                         if (!((xmax < 0.0f) || (ymax < 0.0f) || (xmin > 1.0f) || (ymin > 1.0f))) {
482
483                                 CLAMP(xmin, 0.0f,  1.0f);
484                                 CLAMP(ymin, 0.0f,  1.0f);
485                                 CLAMP(xmax, 0.0f,  1.0f);
486                                 CLAMP(ymax, 0.0f,  1.0f);
487
488                                 {
489                                         unsigned int xi_min = (unsigned int) ((xmin - layer->bounds.xmin) * layer->buckets_xy_scalar[0]);
490                                         unsigned int xi_max = (unsigned int) ((xmax - layer->bounds.xmin) * layer->buckets_xy_scalar[0]);
491                                         unsigned int yi_min = (unsigned int) ((ymin - layer->bounds.ymin) * layer->buckets_xy_scalar[1]);
492                                         unsigned int yi_max = (unsigned int) ((ymax - layer->bounds.ymin) * layer->buckets_xy_scalar[1]);
493                                         void *face_index_void = POINTER_FROM_UINT(face_index);
494
495                                         unsigned int xi, yi;
496
497                                         /* this should _almost_ never happen but since it can in extreme cases,
498                                          * we have to clamp the values or we overrun the buffer and crash */
499                                         if (xi_min >= layer->buckets_x) xi_min = layer->buckets_x - 1;
500                                         if (xi_max >= layer->buckets_x) xi_max = layer->buckets_x - 1;
501                                         if (yi_min >= layer->buckets_y) yi_min = layer->buckets_y - 1;
502                                         if (yi_max >= layer->buckets_y) yi_max = layer->buckets_y - 1;
503
504                                         for (yi = yi_min; yi <= yi_max; yi++) {
505                                                 unsigned int bucket_index = (layer->buckets_x * yi) + xi_min;
506                                                 for (xi = xi_min; xi <= xi_max; xi++, bucket_index++) {
507                                                         // unsigned int bucket_index = (layer->buckets_x * yi) + xi; /* correct but do in outer loop */
508
509                                                         BLI_assert(xi < layer->buckets_x);
510                                                         BLI_assert(yi < layer->buckets_y);
511                                                         BLI_assert(bucket_index < bucket_tot);
512
513                                                         /* check if the bucket intersects with the face */
514                                                         /* note: there is a trade off here since checking box/tri intersections isn't
515                                                          * as optimal as it could be, but checking pixels against faces they will never intersect
516                                                          * with is likely the greater slowdown here - so check if the cell intersects the face */
517                                                         if (layer_bucket_isect_test(layer, face_index,
518                                                                                     xi, yi,
519                                                                                     bucket_size_x, bucket_size_y,
520                                                                                     bucket_max_rad_squared))
521                                                         {
522                                                                 BLI_linklist_prepend_arena(&bucketstore[bucket_index], face_index_void, arena);
523                                                                 bucketstore_tot[bucket_index]++;
524                                                         }
525                                                 }
526                                         }
527                                 }
528                         }
529                 }
530
531                 if (1) {
532                         /* now convert linknodes into arrays for faster per pixel access */
533                         unsigned int  **buckets_face = MEM_mallocN(bucket_tot * sizeof(*buckets_face), __func__);
534                         unsigned int bucket_index;
535
536                         for (bucket_index = 0; bucket_index < bucket_tot; bucket_index++) {
537                                 if (bucketstore_tot[bucket_index]) {
538                                         unsigned int  *bucket = MEM_mallocN((bucketstore_tot[bucket_index] + 1) * sizeof(unsigned int),
539                                                                             __func__);
540                                         LinkNode *bucket_node;
541
542                                         buckets_face[bucket_index] = bucket;
543
544                                         for (bucket_node = bucketstore[bucket_index]; bucket_node; bucket_node = bucket_node->next) {
545                                                 *bucket = POINTER_AS_UINT(bucket_node->link);
546                                                 bucket++;
547                                         }
548                                         *bucket = TRI_TERMINATOR_ID;
549                                 }
550                                 else {
551                                         buckets_face[bucket_index] = NULL;
552                                 }
553                         }
554
555                         layer->buckets_face = buckets_face;
556                 }
557
558                 MEM_freeN(bucketstore);
559                 MEM_freeN(bucketstore_tot);
560         }
561
562         BLI_memarena_free(arena);
563 }
564
565 void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, struct Mask *mask,
566                                    const int width, const int height,
567                                    const bool do_aspect_correct, const bool do_mask_aa,
568                                    const bool do_feather)
569 {
570         const rctf default_bounds = {0.0f, 1.0f, 0.0f, 1.0f};
571         const float pixel_size = 1.0f / (float)min_ii(width, height);
572         const float asp_xy[2] = {(do_aspect_correct && width > height) ? (float)height / (float)width  : 1.0f,
573                                  (do_aspect_correct && width < height) ? (float)width  / (float)height : 1.0f};
574
575         const float zvec[3] = {0.0f, 0.0f, 1.0f};
576         MaskLayer *masklay;
577         unsigned int masklay_index;
578         MemArena *sf_arena;
579
580         mr_handle->layers_tot = (unsigned int)BLI_listbase_count(&mask->masklayers);
581         mr_handle->layers = MEM_mallocN(sizeof(MaskRasterLayer) * mr_handle->layers_tot, "MaskRasterLayer");
582         BLI_rctf_init_minmax(&mr_handle->bounds);
583
584         sf_arena = BLI_memarena_new(BLI_SCANFILL_ARENA_SIZE, __func__);
585
586         for (masklay = mask->masklayers.first, masklay_index = 0; masklay; masklay = masklay->next, masklay_index++) {
587
588                 /* we need to store vertex ranges for open splines for filling */
589                 unsigned int tot_splines;
590                 MaskRasterSplineInfo *open_spline_ranges;
591                 unsigned int   open_spline_index = 0;
592
593                 MaskSpline *spline;
594
595                 /* scanfill */
596                 ScanFillContext sf_ctx;
597                 ScanFillVert *sf_vert = NULL;
598                 ScanFillVert *sf_vert_next = NULL;
599                 ScanFillFace *sf_tri;
600
601                 unsigned int sf_vert_tot = 0;
602                 unsigned int tot_feather_quads = 0;
603
604 #ifdef USE_SCANFILL_EDGE_WORKAROUND
605                 unsigned int tot_boundary_used = 0;
606                 unsigned int tot_boundary_found = 0;
607 #endif
608
609                 if (masklay->restrictflag & MASK_RESTRICT_RENDER) {
610                         /* skip the layer */
611                         mr_handle->layers_tot--;
612                         masklay_index--;
613                         continue;
614                 }
615
616                 tot_splines = (unsigned int)BLI_listbase_count(&masklay->splines);
617                 open_spline_ranges = MEM_callocN(sizeof(*open_spline_ranges) * tot_splines, __func__);
618
619                 BLI_scanfill_begin_arena(&sf_ctx, sf_arena);
620
621                 for (spline = masklay->splines.first; spline; spline = spline->next) {
622                         const bool is_cyclic = (spline->flag & MASK_SPLINE_CYCLIC) != 0;
623                         const bool is_fill = (spline->flag & MASK_SPLINE_NOFILL) == 0;
624
625                         float (*diff_points)[2];
626                         unsigned int tot_diff_point;
627
628                         float (*diff_feather_points)[2];
629                         float (*diff_feather_points_flip)[2];
630                         unsigned int tot_diff_feather_points;
631
632                         const unsigned int resol_a = BKE_mask_spline_resolution(spline, width, height) / 4;
633                         const unsigned int resol_b = BKE_mask_spline_feather_resolution(spline, width, height) / 4;
634                         const unsigned int resol = CLAMPIS(MAX2(resol_a, resol_b), 4, 512);
635
636                         diff_points = BKE_mask_spline_differentiate_with_resolution(
637                                           spline, &tot_diff_point, resol);
638
639                         if (do_feather) {
640                                 diff_feather_points = BKE_mask_spline_feather_differentiated_points_with_resolution(
641                                                           spline, &tot_diff_feather_points, resol, false);
642                                 BLI_assert(diff_feather_points);
643                         }
644                         else {
645                                 tot_diff_feather_points = 0;
646                                 diff_feather_points = NULL;
647                         }
648
649                         if (tot_diff_point > 3) {
650                                 ScanFillVert *sf_vert_prev;
651                                 unsigned int j;
652
653                                 float co[3];
654                                 co[2] = 0.0f;
655
656                                 sf_ctx.poly_nr++;
657
658                                 if (do_aspect_correct) {
659                                         if (width != height) {
660                                                 float *fp;
661                                                 float *ffp;
662                                                 unsigned int i;
663                                                 float asp;
664
665                                                 if (width < height) {
666                                                         fp = &diff_points[0][0];
667                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][0] : NULL;
668                                                         asp = (float)width / (float)height;
669                                                 }
670                                                 else {
671                                                         fp = &diff_points[0][1];
672                                                         ffp = tot_diff_feather_points ? &diff_feather_points[0][1] : NULL;
673                                                         asp = (float)height / (float)width;
674                                                 }
675
676                                                 for (i = 0; i < tot_diff_point; i++, fp += 2) {
677                                                         (*fp) = (((*fp) - 0.5f) / asp) + 0.5f;
678                                                 }
679
680                                                 if (tot_diff_feather_points) {
681                                                         for (i = 0; i < tot_diff_feather_points; i++, ffp += 2) {
682                                                                 (*ffp) = (((*ffp) - 0.5f) / asp) + 0.5f;
683                                                         }
684                                                 }
685                                         }
686                                 }
687
688                                 /* fake aa, using small feather */
689                                 if (do_mask_aa == true) {
690                                         if (do_feather == false) {
691                                                 tot_diff_feather_points = tot_diff_point;
692                                                 diff_feather_points = MEM_mallocN(sizeof(*diff_feather_points) *
693                                                                                   (size_t)tot_diff_feather_points,
694                                                                                   __func__);
695                                                 /* add single pixel feather */
696                                                 maskrasterize_spline_differentiate_point_outset(diff_feather_points, diff_points,
697                                                                                                tot_diff_point, pixel_size, false);
698                                         }
699                                         else {
700                                                 /* ensure single pixel feather, on any zero feather areas */
701                                                 maskrasterize_spline_differentiate_point_outset(diff_feather_points, diff_points,
702                                                                                                tot_diff_point, pixel_size, true);
703                                         }
704                                 }
705
706                                 if (is_fill) {
707                                         /* applt intersections depending on fill settings */
708                                         if (spline->flag & MASK_SPLINE_NOINTERSECT) {
709                                                 BKE_mask_spline_feather_collapse_inner_loops(spline, diff_feather_points, tot_diff_feather_points);
710                                         }
711
712                                         copy_v2_v2(co, diff_points[0]);
713                                         sf_vert_prev = BLI_scanfill_vert_add(&sf_ctx, co);
714                                         sf_vert_prev->tmp.u = sf_vert_tot;
715                                         sf_vert_prev->keyindex = sf_vert_tot + tot_diff_point; /* absolute index of feather vert */
716                                         sf_vert_tot++;
717
718                                         /* TODO, an alternate functions so we can avoid double vector copy! */
719                                         for (j = 1; j < tot_diff_point; j++) {
720                                                 copy_v2_v2(co, diff_points[j]);
721                                                 sf_vert = BLI_scanfill_vert_add(&sf_ctx, co);
722                                                 sf_vert->tmp.u = sf_vert_tot;
723                                                 sf_vert->keyindex = sf_vert_tot + tot_diff_point; /* absolute index of feather vert */
724                                                 sf_vert_tot++;
725                                         }
726
727                                         sf_vert = sf_vert_prev;
728                                         sf_vert_prev = sf_ctx.fillvertbase.last;
729
730                                         for (j = 0; j < tot_diff_point; j++) {
731                                                 ScanFillEdge *sf_edge = BLI_scanfill_edge_add(&sf_ctx, sf_vert_prev, sf_vert);
732
733 #ifdef USE_SCANFILL_EDGE_WORKAROUND
734                                                 if (diff_feather_points) {
735                                                         sf_edge->tmp.c = SF_EDGE_IS_BOUNDARY;
736                                                         tot_boundary_used++;
737                                                 }
738 #else
739                                                 (void)sf_edge;
740 #endif
741                                                 sf_vert_prev = sf_vert;
742                                                 sf_vert = sf_vert->next;
743                                         }
744
745                                         if (diff_feather_points) {
746                                                 float co_feather[3];
747                                                 co_feather[2] = 1.0f;
748
749                                                 BLI_assert(tot_diff_feather_points == tot_diff_point);
750
751                                                 /* note: only added for convenience, we don't infact use these to scanfill,
752                                                  * only to create feather faces after scanfill */
753                                                 for (j = 0; j < tot_diff_feather_points; j++) {
754                                                         copy_v2_v2(co_feather, diff_feather_points[j]);
755                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co_feather);
756                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
757                                                         sf_vert_tot++;
758                                                 }
759
760                                                 tot_feather_quads += tot_diff_point;
761                                         }
762                                 }
763                                 else {
764                                         /* unfilled spline */
765                                         if (diff_feather_points) {
766
767                                                 float co_diff[2];
768
769                                                 float co_feather[3];
770                                                 co_feather[2] = 1.0f;
771
772                                                 if (spline->flag & MASK_SPLINE_NOINTERSECT) {
773                                                         diff_feather_points_flip = MEM_mallocN(sizeof(float) * 2 * tot_diff_feather_points, "diff_feather_points_flip");
774
775                                                         for (j = 0; j < tot_diff_point; j++) {
776                                                                 sub_v2_v2v2(co_diff, diff_points[j], diff_feather_points[j]);
777                                                                 add_v2_v2v2(diff_feather_points_flip[j], diff_points[j], co_diff);
778                                                         }
779
780                                                         BKE_mask_spline_feather_collapse_inner_loops(spline, diff_feather_points,      tot_diff_feather_points);
781                                                         BKE_mask_spline_feather_collapse_inner_loops(spline, diff_feather_points_flip, tot_diff_feather_points);
782                                                 }
783                                                 else {
784                                                         diff_feather_points_flip = NULL;
785                                                 }
786
787
788                                                 open_spline_ranges[open_spline_index].vertex_offset = sf_vert_tot;
789                                                 open_spline_ranges[open_spline_index].vertex_total = tot_diff_point;
790
791                                                 /* TODO, an alternate functions so we can avoid double vector copy! */
792                                                 for (j = 0; j < tot_diff_point; j++) {
793
794                                                         /* center vert */
795                                                         copy_v2_v2(co, diff_points[j]);
796                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co);
797                                                         sf_vert->tmp.u = sf_vert_tot;
798                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
799                                                         sf_vert_tot++;
800
801
802                                                         /* feather vert A */
803                                                         copy_v2_v2(co_feather, diff_feather_points[j]);
804                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co_feather);
805                                                         sf_vert->tmp.u = sf_vert_tot;
806                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
807                                                         sf_vert_tot++;
808
809
810                                                         /* feather vert B */
811                                                         if (diff_feather_points_flip) {
812                                                                 copy_v2_v2(co_feather, diff_feather_points_flip[j]);
813                                                         }
814                                                         else {
815                                                                 sub_v2_v2v2(co_diff, co, co_feather);
816                                                                 add_v2_v2v2(co_feather, co, co_diff);
817                                                         }
818
819                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co_feather);
820                                                         sf_vert->tmp.u = sf_vert_tot;
821                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
822                                                         sf_vert_tot++;
823
824                                                         tot_feather_quads += 2;
825                                                 }
826
827                                                 if (!is_cyclic) {
828                                                         tot_feather_quads -= 2;
829                                                 }
830
831                                                 if (diff_feather_points_flip) {
832                                                         MEM_freeN(diff_feather_points_flip);
833                                                         diff_feather_points_flip = NULL;
834                                                 }
835
836                                                 /* cap ends */
837
838                                                 /* dummy init value */
839                                                 open_spline_ranges[open_spline_index].vertex_total_cap_head = 0;
840                                                 open_spline_ranges[open_spline_index].vertex_total_cap_tail = 0;
841
842                                                 if (!is_cyclic) {
843                                                         const float *fp_cent;
844                                                         const float *fp_turn;
845
846                                                         unsigned int k;
847
848                                                         fp_cent = diff_points[0];
849                                                         fp_turn = diff_feather_points[0];
850
851 #define CALC_CAP_RESOL                                                                      \
852         clampis_uint((unsigned int )(len_v2v2(fp_cent, fp_turn) /                               \
853                                      (pixel_size * SPLINE_RESOL_CAP_PER_PIXEL)),                \
854                      SPLINE_RESOL_CAP_MIN, SPLINE_RESOL_CAP_MAX)
855
856                                                         {
857                                                                 const unsigned int vertex_total_cap = CALC_CAP_RESOL;
858
859                                                                 for (k = 1; k < vertex_total_cap; k++) {
860                                                                         const float angle = (float)k * (1.0f / (float)vertex_total_cap) * (float)M_PI;
861                                                                         rotate_point_v2(co_feather, fp_turn, fp_cent, angle, asp_xy);
862
863                                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co_feather);
864                                                                         sf_vert->tmp.u = sf_vert_tot;
865                                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
866                                                                         sf_vert_tot++;
867                                                                 }
868                                                                 tot_feather_quads += vertex_total_cap;
869
870                                                                 open_spline_ranges[open_spline_index].vertex_total_cap_head = vertex_total_cap;
871                                                         }
872
873                                                         fp_cent = diff_points[tot_diff_point - 1];
874                                                         fp_turn = diff_feather_points[tot_diff_point - 1];
875
876                                                         {
877                                                                 const unsigned int vertex_total_cap = CALC_CAP_RESOL;
878
879                                                                 for (k = 1; k < vertex_total_cap; k++) {
880                                                                         const float angle = (float)k * (1.0f / (float)vertex_total_cap) * (float)M_PI;
881                                                                         rotate_point_v2(co_feather, fp_turn, fp_cent, -angle, asp_xy);
882
883                                                                         sf_vert = BLI_scanfill_vert_add(&sf_ctx, co_feather);
884                                                                         sf_vert->tmp.u = sf_vert_tot;
885                                                                         sf_vert->keyindex = SF_KEYINDEX_TEMP_ID;
886                                                                         sf_vert_tot++;
887                                                                 }
888                                                                 tot_feather_quads += vertex_total_cap;
889
890                                                                 open_spline_ranges[open_spline_index].vertex_total_cap_tail = vertex_total_cap;
891                                                         }
892                                                 }
893
894                                                 open_spline_ranges[open_spline_index].is_cyclic = is_cyclic;
895                                                 open_spline_index++;
896
897 #undef CALC_CAP_RESOL
898                                                 /* end capping */
899
900                                         }
901                                 }
902                         }
903
904                         if (diff_points) {
905                                 MEM_freeN(diff_points);
906                         }
907
908                         if (diff_feather_points) {
909                                 MEM_freeN(diff_feather_points);
910                         }
911                 }
912
913                 {
914                         unsigned int (*face_array)[4], *face;  /* access coords */
915                         float        (*face_coords)[3], *cos; /* xy, z 0-1 (1.0 == filled) */
916                         unsigned int sf_tri_tot;
917                         rctf bounds;
918                         unsigned int face_index;
919                         int scanfill_flag = 0;
920
921                         bool is_isect = false;
922                         ListBase isect_remvertbase = {NULL, NULL};
923                         ListBase isect_remedgebase = {NULL, NULL};
924
925                         /* now we have all the splines */
926                         face_coords = MEM_mallocN((sizeof(float) * 3) * sf_vert_tot, "maskrast_face_coords");
927
928                         /* init bounds */
929                         BLI_rctf_init_minmax(&bounds);
930
931                         /* coords */
932                         cos = (float *)face_coords;
933                         for (sf_vert = sf_ctx.fillvertbase.first; sf_vert; sf_vert = sf_vert_next) {
934                                 sf_vert_next = sf_vert->next;
935                                 copy_v3_v3(cos, sf_vert->co);
936
937                                 /* remove so as not to interfere with fill (called after) */
938                                 if (sf_vert->keyindex == SF_KEYINDEX_TEMP_ID) {
939                                         BLI_remlink(&sf_ctx.fillvertbase, sf_vert);
940                                 }
941
942                                 /* bounds */
943                                 BLI_rctf_do_minmax_v(&bounds, cos);
944
945                                 cos += 3;
946                         }
947
948
949                         /* --- inefficient self-intersect case --- */
950                         /* if self intersections are found, its too trickty to attempt to map vertices
951                          * so just realloc and add entirely new vertices - the result of the self-intersect check
952                          */
953                         if ((masklay->flag & MASK_LAYERFLAG_FILL_OVERLAP) &&
954                             (is_isect = BLI_scanfill_calc_self_isect(&sf_ctx,
955                                                                      &isect_remvertbase,
956                                                                      &isect_remedgebase)))
957                         {
958                                 unsigned int sf_vert_tot_isect = (unsigned int)BLI_listbase_count(&sf_ctx.fillvertbase);
959                                 unsigned int i = sf_vert_tot;
960
961                                 face_coords = MEM_reallocN(face_coords, sizeof(float[3]) * (sf_vert_tot + sf_vert_tot_isect));
962
963                                 cos = (float *)&face_coords[sf_vert_tot][0];
964
965                                 for (sf_vert = sf_ctx.fillvertbase.first; sf_vert; sf_vert = sf_vert->next) {
966                                         copy_v3_v3(cos, sf_vert->co);
967                                         sf_vert->tmp.u = i++;
968                                         cos += 3;
969                                 }
970
971                                 sf_vert_tot += sf_vert_tot_isect;
972
973                                 /* we need to calc polys after self intersect */
974                                 scanfill_flag |= BLI_SCANFILL_CALC_POLYS;
975                         }
976                         /* --- end inefficient code --- */
977
978
979                         /* main scan-fill */
980                         if ((masklay->flag & MASK_LAYERFLAG_FILL_DISCRETE) == 0)
981                                 scanfill_flag |= BLI_SCANFILL_CALC_HOLES;
982
983                         sf_tri_tot = (unsigned int)BLI_scanfill_calc_ex(&sf_ctx, scanfill_flag, zvec);
984
985                         if (is_isect) {
986                                 /* add removed data back, we only need edges for feather,
987                                  * but add verts back so they get freed along with others */
988                                 BLI_movelisttolist(&sf_ctx.fillvertbase, &isect_remvertbase);
989                                 BLI_movelisttolist(&sf_ctx.filledgebase, &isect_remedgebase);
990                         }
991
992                         face_array = MEM_mallocN(sizeof(*face_array) * ((size_t)sf_tri_tot + (size_t)tot_feather_quads), "maskrast_face_index");
993                         face_index = 0;
994
995                         /* faces */
996                         face = (unsigned int *)face_array;
997                         for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next) {
998                                 *(face++) = sf_tri->v3->tmp.u;
999                                 *(face++) = sf_tri->v2->tmp.u;
1000                                 *(face++) = sf_tri->v1->tmp.u;
1001                                 *(face++) = TRI_VERT;
1002                                 face_index++;
1003                                 FACE_ASSERT(face - 4, sf_vert_tot);
1004                         }
1005
1006                         /* start of feather faces... if we have this set,
1007                          * 'face_index' is kept from loop above */
1008
1009                         BLI_assert(face_index == sf_tri_tot);
1010
1011                         if (tot_feather_quads) {
1012                                 ScanFillEdge *sf_edge;
1013
1014                                 for (sf_edge = sf_ctx.filledgebase.first; sf_edge; sf_edge = sf_edge->next) {
1015                                         if (sf_edge->tmp.c == SF_EDGE_IS_BOUNDARY) {
1016                                                 *(face++) = sf_edge->v1->tmp.u;
1017                                                 *(face++) = sf_edge->v2->tmp.u;
1018                                                 *(face++) = sf_edge->v2->keyindex;
1019                                                 *(face++) = sf_edge->v1->keyindex;
1020                                                 face_index++;
1021                                                 FACE_ASSERT(face - 4, sf_vert_tot);
1022
1023 #ifdef USE_SCANFILL_EDGE_WORKAROUND
1024                                                 tot_boundary_found++;
1025 #endif
1026                                         }
1027                                 }
1028                         }
1029
1030 #ifdef USE_SCANFILL_EDGE_WORKAROUND
1031                         if (tot_boundary_found != tot_boundary_used) {
1032                                 BLI_assert(tot_boundary_found < tot_boundary_used);
1033                         }
1034 #endif
1035
1036                         /* feather only splines */
1037                         while (open_spline_index > 0) {
1038                                 const unsigned int vertex_offset         = open_spline_ranges[--open_spline_index].vertex_offset;
1039                                 unsigned int       vertex_total          = open_spline_ranges[  open_spline_index].vertex_total;
1040                                 unsigned int       vertex_total_cap_head = open_spline_ranges[  open_spline_index].vertex_total_cap_head;
1041                                 unsigned int       vertex_total_cap_tail = open_spline_ranges[  open_spline_index].vertex_total_cap_tail;
1042                                 unsigned int k, j;
1043
1044                                 j = vertex_offset;
1045
1046                                 /* subtract one since we reference next vertex triple */
1047                                 for (k = 0; k < vertex_total - 1; k++, j += 3) {
1048
1049                                         BLI_assert(j == vertex_offset + (k * 3));
1050
1051                                         *(face++) = j + 3; /* next span */ /* z 1 */
1052                                         *(face++) = j + 0;                 /* z 1 */
1053                                         *(face++) = j + 1;                 /* z 0 */
1054                                         *(face++) = j + 4; /* next span */ /* z 0 */
1055                                         face_index++;
1056                                         FACE_ASSERT(face - 4, sf_vert_tot);
1057
1058                                         *(face++) = j + 0;                 /* z 1 */
1059                                         *(face++) = j + 3; /* next span */ /* z 1 */
1060                                         *(face++) = j + 5; /* next span */ /* z 0 */
1061                                         *(face++) = j + 2;                 /* z 0 */
1062                                         face_index++;
1063                                         FACE_ASSERT(face - 4, sf_vert_tot);
1064                                 }
1065
1066                                 if (open_spline_ranges[open_spline_index].is_cyclic) {
1067                                         *(face++) = vertex_offset + 0; /* next span */ /* z 1 */
1068                                         *(face++) = j             + 0;                 /* z 1 */
1069                                         *(face++) = j             + 1;                 /* z 0 */
1070                                         *(face++) = vertex_offset + 1; /* next span */ /* z 0 */
1071                                         face_index++;
1072                                         FACE_ASSERT(face - 4, sf_vert_tot);
1073
1074                                         *(face++) = j          + 0;                    /* z 1 */
1075                                         *(face++) = vertex_offset + 0; /* next span */ /* z 1 */
1076                                         *(face++) = vertex_offset + 2; /* next span */ /* z 0 */
1077                                         *(face++) = j          + 2;                    /* z 0 */
1078                                         face_index++;
1079                                         FACE_ASSERT(face - 4, sf_vert_tot);
1080                                 }
1081                                 else {
1082                                         unsigned int midvidx = vertex_offset;
1083
1084                                         /***************
1085                                          * cap end 'a' */
1086                                         j = midvidx + (vertex_total * 3);
1087
1088                                         for (k = 0; k < vertex_total_cap_head - 2; k++, j++) {
1089                                                 *(face++) = midvidx + 0;  /* z 1 */
1090                                                 *(face++) = midvidx + 0;  /* z 1 */
1091                                                 *(face++) = j + 0;        /* z 0 */
1092                                                 *(face++) = j + 1;        /* z 0 */
1093                                                 face_index++;
1094                                                 FACE_ASSERT(face - 4, sf_vert_tot);
1095                                         }
1096
1097                                         j = vertex_offset + (vertex_total * 3);
1098
1099                                         /* 2 tris that join the original */
1100                                         *(face++) = midvidx + 0;  /* z 1 */
1101                                         *(face++) = midvidx + 0;  /* z 1 */
1102                                         *(face++) = midvidx + 1;  /* z 0 */
1103                                         *(face++) = j + 0;        /* z 0 */
1104                                         face_index++;
1105                                         FACE_ASSERT(face - 4, sf_vert_tot);
1106
1107                                         *(face++) = midvidx + 0;                    /* z 1 */
1108                                         *(face++) = midvidx + 0;                    /* z 1 */
1109                                         *(face++) = j + vertex_total_cap_head - 2;  /* z 0 */
1110                                         *(face++) = midvidx + 2;                    /* z 0 */
1111                                         face_index++;
1112                                         FACE_ASSERT(face - 4, sf_vert_tot);
1113
1114
1115                                         /***************
1116                                          * cap end 'b' */
1117                                         /* ... same as previous but v 2-3 flipped, and different initial offsets */
1118
1119                                         j = vertex_offset + (vertex_total * 3) + (vertex_total_cap_head - 1);
1120
1121                                         midvidx = vertex_offset + (vertex_total * 3) - 3;
1122
1123                                         for (k = 0; k < vertex_total_cap_tail - 2; k++, j++) {
1124                                                 *(face++) = midvidx;  /* z 1 */
1125                                                 *(face++) = midvidx;  /* z 1 */
1126                                                 *(face++) = j + 1;    /* z 0 */
1127                                                 *(face++) = j + 0;    /* z 0 */
1128                                                 face_index++;
1129                                                 FACE_ASSERT(face - 4, sf_vert_tot);
1130                                         }
1131
1132                                         j = vertex_offset + (vertex_total * 3) + (vertex_total_cap_head - 1);
1133
1134                                         /* 2 tris that join the original */
1135                                         *(face++) = midvidx + 0;  /* z 1 */
1136                                         *(face++) = midvidx + 0;  /* z 1 */
1137                                         *(face++) = j + 0;        /* z 0 */
1138                                         *(face++) = midvidx + 1;  /* z 0 */
1139                                         face_index++;
1140                                         FACE_ASSERT(face - 4, sf_vert_tot);
1141
1142                                         *(face++) = midvidx + 0;                    /* z 1 */
1143                                         *(face++) = midvidx + 0;                    /* z 1 */
1144                                         *(face++) = midvidx + 2;                    /* z 0 */
1145                                         *(face++) = j + vertex_total_cap_tail - 2;  /* z 0 */
1146                                         face_index++;
1147                                         FACE_ASSERT(face - 4, sf_vert_tot);
1148
1149                                 }
1150                         }
1151
1152                         MEM_freeN(open_spline_ranges);
1153
1154 //                      fprintf(stderr, "%u %u (%u %u), %u\n", face_index, sf_tri_tot + tot_feather_quads, sf_tri_tot, tot_feather_quads, tot_boundary_used - tot_boundary_found);
1155
1156 #ifdef USE_SCANFILL_EDGE_WORKAROUND
1157                         BLI_assert(face_index + (tot_boundary_used - tot_boundary_found) == sf_tri_tot + tot_feather_quads);
1158 #else
1159                         BLI_assert(face_index == sf_tri_tot + tot_feather_quads);
1160 #endif
1161                         {
1162                                 MaskRasterLayer *layer = &mr_handle->layers[masklay_index];
1163
1164                                 if (BLI_rctf_isect(&default_bounds, &bounds, &bounds)) {
1165 #ifdef USE_SCANFILL_EDGE_WORKAROUND
1166                                         layer->face_tot = (sf_tri_tot + tot_feather_quads) - (tot_boundary_used - tot_boundary_found);
1167 #else
1168                                         layer->face_tot = (sf_tri_tot + tot_feather_quads);
1169 #endif
1170                                         layer->face_coords = face_coords;
1171                                         layer->face_array  = face_array;
1172                                         layer->bounds = bounds;
1173
1174                                         layer_bucket_init(layer, pixel_size);
1175
1176                                         BLI_rctf_union(&mr_handle->bounds, &bounds);
1177                                 }
1178                                 else {
1179                                         MEM_freeN(face_coords);
1180                                         MEM_freeN(face_array);
1181
1182                                         layer_bucket_init_dummy(layer);
1183                                 }
1184
1185                                 /* copy as-is */
1186                                 layer->alpha = masklay->alpha;
1187                                 layer->blend = masklay->blend;
1188                                 layer->blend_flag = masklay->blend_flag;
1189                                 layer->falloff = masklay->falloff;
1190                         }
1191
1192                         /* printf("tris %d, feather tris %d\n", sf_tri_tot, tot_feather_quads); */
1193                 }
1194
1195                 /* add trianges */
1196                 BLI_scanfill_end_arena(&sf_ctx, sf_arena);
1197         }
1198
1199         BLI_memarena_free(sf_arena);
1200 }
1201
1202
1203 /* --------------------------------------------------------------------- */
1204 /* functions that run inside the sampling thread (keep fast!)            */
1205 /* --------------------------------------------------------------------- */
1206
1207 /* 2D ray test */
1208 #if 0
1209 static float maskrasterize_layer_z_depth_tri(const float pt[2],
1210                                              const float v1[3], const float v2[3], const float v3[3])
1211 {
1212         float w[3];
1213         barycentric_weights_v2(v1, v2, v3, pt, w);
1214         return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]);
1215 }
1216 #endif
1217
1218 static float maskrasterize_layer_z_depth_quad(const float pt[2],
1219                                               const float v1[3], const float v2[3], const float v3[3], const float v4[3])
1220 {
1221         float w[4];
1222         barycentric_weights_v2_quad(v1, v2, v3, v4, pt, w);
1223         //return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]) + (v4[2] * w[3]);
1224         return w[2] + w[3];  /* we can make this assumption for small speedup */
1225 }
1226
1227 static float maskrasterize_layer_isect(unsigned int *face, float (*cos)[3], const float dist_orig, const float xy[2])
1228 {
1229         /* we always cast from same place only need xy */
1230         if (face[3] == TRI_VERT) {
1231                 /* --- tri --- */
1232
1233 #if 0
1234                 /* not essential but avoids unneeded extra lookups */
1235                 if ((cos[0][2] < dist_orig) ||
1236                     (cos[1][2] < dist_orig) ||
1237                     (cos[2][2] < dist_orig))
1238                 {
1239                         if (isect_point_tri_v2_cw(xy, cos[face[0]], cos[face[1]], cos[face[2]])) {
1240                                 /* we know all tris are close for now */
1241                                 return maskrasterize_layer_z_depth_tri(xy, cos[face[0]], cos[face[1]], cos[face[2]]);
1242                         }
1243                 }
1244 #else
1245                 /* we know all tris are close for now */
1246                 if (isect_point_tri_v2_cw(xy, cos[face[0]], cos[face[1]], cos[face[2]])) {
1247                         return 0.0f;
1248                 }
1249 #endif
1250         }
1251         else {
1252                 /* --- quad --- */
1253
1254                 /* not essential but avoids unneeded extra lookups */
1255                 if ((cos[0][2] < dist_orig) ||
1256                     (cos[1][2] < dist_orig) ||
1257                     (cos[2][2] < dist_orig) ||
1258                     (cos[3][2] < dist_orig))
1259                 {
1260
1261                         /* needs work */
1262 #if 1
1263                         /* quad check fails for bow-tie, so keep using 2 tri checks */
1264                         //if (isect_point_quad_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]]))
1265                         if (isect_point_tri_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]]) ||
1266                             isect_point_tri_v2(xy, cos[face[0]], cos[face[2]], cos[face[3]]))
1267                         {
1268                                 return maskrasterize_layer_z_depth_quad(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]]);
1269                         }
1270 #elif 1
1271                         /* don't use isect_point_tri_v2_cw because we could have bow-tie quads */
1272
1273                         if (isect_point_tri_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]])) {
1274                                 return maskrasterize_layer_z_depth_tri(xy, cos[face[0]], cos[face[1]], cos[face[2]]);
1275                         }
1276                         else if (isect_point_tri_v2(xy, cos[face[0]], cos[face[2]], cos[face[3]])) {
1277                                 return maskrasterize_layer_z_depth_tri(xy, cos[face[0]], cos[face[2]], cos[face[3]]);
1278                         }
1279 #else
1280                         /* cheat - we know first 2 verts are z0.0f and second 2 are z 1.0f */
1281                         /* ... worth looking into */
1282 #endif
1283                 }
1284         }
1285
1286         return 1.0f;
1287 }
1288
1289 BLI_INLINE unsigned int layer_bucket_index_from_xy(MaskRasterLayer *layer, const float xy[2])
1290 {
1291         BLI_assert(BLI_rctf_isect_pt_v(&layer->bounds, xy));
1292
1293         return ( (unsigned int)((xy[0] - layer->bounds.xmin) * layer->buckets_xy_scalar[0])) +
1294                (((unsigned int)((xy[1] - layer->bounds.ymin) * layer->buckets_xy_scalar[1])) * layer->buckets_x);
1295 }
1296
1297 static float layer_bucket_depth_from_xy(MaskRasterLayer *layer, const float xy[2])
1298 {
1299         unsigned int index = layer_bucket_index_from_xy(layer, xy);
1300         unsigned int *face_index = layer->buckets_face[index];
1301
1302         if (face_index) {
1303                 unsigned int (*face_array)[4] = layer->face_array;
1304                 float        (*cos)[3]        = layer->face_coords;
1305                 float best_dist = 1.0f;
1306                 while (*face_index != TRI_TERMINATOR_ID) {
1307                         const float test_dist = maskrasterize_layer_isect(face_array[*face_index], cos, best_dist, xy);
1308                         if (test_dist < best_dist) {
1309                                 best_dist = test_dist;
1310                                 /* comparing with 0.0f is OK here because triangles are always zero depth */
1311                                 if (best_dist == 0.0f) {
1312                                         /* bail early, we're as close as possible */
1313                                         return 0.0f;
1314                                 }
1315                         }
1316                         face_index++;
1317                 }
1318                 return best_dist;
1319         }
1320         else {
1321                 return 1.0f;
1322         }
1323 }
1324
1325 float BKE_maskrasterize_handle_sample(MaskRasterHandle *mr_handle, const float xy[2])
1326 {
1327         /* can't do this because some layers may invert */
1328         /* if (BLI_rctf_isect_pt_v(&mr_handle->bounds, xy)) */
1329
1330         const unsigned int layers_tot = mr_handle->layers_tot;
1331         unsigned int i;
1332         MaskRasterLayer *layer = mr_handle->layers;
1333
1334         /* return value */
1335         float value = 0.0f;
1336
1337         for (i = 0; i < layers_tot; i++, layer++) {
1338                 float value_layer;
1339
1340                 /* also used as signal for unused layer (when render is disabled) */
1341                 if (layer->alpha != 0.0f && BLI_rctf_isect_pt_v(&layer->bounds, xy)) {
1342                         value_layer = 1.0f - layer_bucket_depth_from_xy(layer, xy);
1343
1344                         switch (layer->falloff) {
1345                                 case PROP_SMOOTH:
1346                                         /* ease - gives less hard lines for dilate/erode feather */
1347                                         value_layer = (3.0f * value_layer * value_layer - 2.0f * value_layer * value_layer * value_layer);
1348                                         break;
1349                                 case PROP_SPHERE:
1350                                         value_layer = sqrtf(2.0f * value_layer - value_layer * value_layer);
1351                                         break;
1352                                 case PROP_ROOT:
1353                                         value_layer = sqrtf(value_layer);
1354                                         break;
1355                                 case PROP_SHARP:
1356                                         value_layer = value_layer * value_layer;
1357                                         break;
1358                                 case PROP_INVSQUARE:
1359                                         value_layer = value_layer * (2.0f - value_layer);
1360                                         break;
1361                                 case PROP_LIN:
1362                                 default:
1363                                         /* nothing */
1364                                         break;
1365                         }
1366
1367                         if (layer->blend != MASK_BLEND_REPLACE) {
1368                                 value_layer *= layer->alpha;
1369                         }
1370                 }
1371                 else {
1372                         value_layer = 0.0f;
1373                 }
1374
1375                 if (layer->blend_flag & MASK_BLENDFLAG_INVERT) {
1376                         value_layer = 1.0f - value_layer;
1377                 }
1378
1379                 switch (layer->blend) {
1380                         case MASK_BLEND_MERGE_ADD:
1381                                 value += value_layer * (1.0f - value);
1382                                 break;
1383                         case MASK_BLEND_MERGE_SUBTRACT:
1384                                 value -= value_layer * value;
1385                                 break;
1386                         case MASK_BLEND_ADD:
1387                                 value += value_layer;
1388                                 break;
1389                         case MASK_BLEND_SUBTRACT:
1390                                 value -= value_layer;
1391                                 break;
1392                         case MASK_BLEND_LIGHTEN:
1393                                 value = max_ff(value, value_layer);
1394                                 break;
1395                         case MASK_BLEND_DARKEN:
1396                                 value = min_ff(value, value_layer);
1397                                 break;
1398                         case MASK_BLEND_MUL:
1399                                 value *= value_layer;
1400                                 break;
1401                         case MASK_BLEND_REPLACE:
1402                                 value = (value * (1.0f - layer->alpha)) + (value_layer * layer->alpha);
1403                                 break;
1404                         case MASK_BLEND_DIFFERENCE:
1405                                 value = fabsf(value - value_layer);
1406                                 break;
1407                         default: /* same as add */
1408                                 CLOG_ERROR(&LOG, "unhandled blend type: %d", layer->blend);
1409                                 BLI_assert(0);
1410                                 value += value_layer;
1411                                 break;
1412                 }
1413
1414                 /* clamp after applying each layer so we don't get
1415                  * issues subtracting after accumulating over 1.0f */
1416                 CLAMP(value, 0.0f, 1.0f);
1417         }
1418
1419         return value;
1420 }
1421
1422
1423 typedef struct MaskRasterizeBufferData {
1424         MaskRasterHandle *mr_handle;
1425         float x_inv, y_inv;
1426         float x_px_ofs, y_px_ofs;
1427         uint width;
1428
1429         float *buffer;
1430 } MaskRasterizeBufferData;
1431
1432 static void maskrasterize_buffer_cb(
1433         void *__restrict userdata,
1434         const int y,
1435         const ParallelRangeTLS *__restrict UNUSED(tls))
1436 {
1437         MaskRasterizeBufferData *data = userdata;
1438
1439         MaskRasterHandle *mr_handle = data->mr_handle;
1440         float *buffer = data->buffer;
1441
1442         const uint width = data->width;
1443         const float x_inv = data->x_inv;
1444         const float x_px_ofs = data->x_px_ofs;
1445
1446         uint i = (uint)y * width;
1447         float xy[2];
1448         xy[1] = ((float)y * data->y_inv) + data->y_px_ofs;
1449         for (uint x = 0; x < width; x++, i++) {
1450                 xy[0] = ((float)x * x_inv) + x_px_ofs;
1451
1452                 buffer[i] = BKE_maskrasterize_handle_sample(mr_handle, xy);
1453         }
1454 }
1455
1456 /**
1457  * \brief Rasterize a buffer from a single mask (threaded execution).
1458  */
1459 void BKE_maskrasterize_buffer(MaskRasterHandle *mr_handle,
1460                               const unsigned int width, const unsigned int height,
1461                               float *buffer)
1462 {
1463         const float x_inv = 1.0f / (float)width;
1464         const float y_inv = 1.0f / (float)height;
1465
1466         MaskRasterizeBufferData data = {
1467             .mr_handle = mr_handle,
1468             .x_inv = x_inv,
1469             .y_inv = y_inv,
1470             .x_px_ofs = x_inv * 0.5f,
1471             .y_px_ofs = y_inv * 0.5f,
1472             .width = width,
1473             .buffer = buffer,
1474         };
1475         ParallelRangeSettings settings;
1476         BLI_parallel_range_settings_defaults(&settings);
1477         settings.use_threading = ((size_t)height * width > 10000);
1478         BLI_task_parallel_range(0, (int)height,
1479                                 &data,
1480                                 maskrasterize_buffer_cb,
1481                                 &settings);
1482 }