3ceaaff2f5d999d8b19865b00e2e495e84e00705
[blender-staging.git] / source / blender / editors / sculpt_paint / paint_image_proj.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  * along with this program; if not, write to the Free Software Foundation,
15  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16  *
17  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
18  * All rights reserved.
19  *
20  * The Original Code is: some of this file.
21  *
22  * Contributor(s): Jens Ole Wund (bjornmose), Campbell Barton (ideasman42)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_image_proj.c
28  *  \ingroup edsculpt
29  *  \brief Functions to paint images in 2D and 3D.
30  */
31
32 #include <float.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #ifdef WIN32
40 #  include "BLI_winstuff.h"
41 #endif
42
43 #include "BLI_blenlib.h"
44 #include "BLI_linklist.h"
45 #include "BLI_math.h"
46 #include "BLI_math_color_blend.h"
47 #include "BLI_memarena.h"
48 #include "BLI_threads.h"
49 #include "BLI_utildefines.h"
50
51 #include "BLF_translation.h"
52
53
54 #include "IMB_imbuf.h"
55 #include "IMB_imbuf_types.h"
56
57 #include "DNA_brush_types.h"
58 #include "DNA_material_types.h"
59 #include "DNA_mesh_types.h"
60 #include "DNA_node_types.h"
61 #include "DNA_object_types.h"
62
63 #include "BKE_camera.h"
64 #include "BKE_context.h"
65 #include "BKE_colortools.h"
66 #include "BKE_depsgraph.h"
67 #include "BKE_DerivedMesh.h"
68 #include "BKE_idprop.h"
69 #include "BKE_brush.h"
70 #include "BKE_image.h"
71 #include "BKE_library.h"
72 #include "BKE_main.h"
73 #include "BKE_material.h"
74 #include "BKE_mesh.h"
75 #include "BKE_mesh_mapping.h"
76 #include "BKE_node.h"
77 #include "BKE_paint.h"
78 #include "BKE_report.h"
79 #include "BKE_scene.h"
80 #include "BKE_texture.h"
81
82 #include "UI_interface.h"
83
84 #include "ED_mesh.h"
85 #include "ED_node.h"
86 #include "ED_paint.h"
87 #include "ED_screen.h"
88 #include "ED_uvedit.h"
89 #include "ED_view3d.h"
90
91 #include "GPU_extensions.h"
92
93 #include "WM_api.h"
94 #include "WM_types.h"
95
96 #include "RNA_access.h"
97 #include "RNA_define.h"
98 #include "RNA_enum_types.h"
99
100 #include "GPU_draw.h"
101
102 #include "IMB_colormanagement.h"
103
104 #include "bmesh.h"
105 //#include "bmesh_tools.h"
106
107 #include "paint_intern.h"
108
109 /* Defines and Structs */
110 /* FTOCHAR as inline function */
111 BLI_INLINE unsigned char f_to_char(const float val)
112 {
113         return FTOCHAR(val);
114 }
115
116 /* ProjectionPaint defines */
117
118 /* approx the number of buckets to have under the brush,
119  * used with the brush size to set the ps->buckets_x and ps->buckets_y value.
120  *
121  * When 3 - a brush should have ~9 buckets under it at once
122  * ...this helps for threading while painting as well as
123  * avoiding initializing pixels that wont touch the brush */
124 #define PROJ_BUCKET_BRUSH_DIV 4
125
126 #define PROJ_BUCKET_RECT_MIN 4
127 #define PROJ_BUCKET_RECT_MAX 256
128
129 #define PROJ_BOUNDBOX_DIV 8
130 #define PROJ_BOUNDBOX_SQUARED  (PROJ_BOUNDBOX_DIV * PROJ_BOUNDBOX_DIV)
131
132 //#define PROJ_DEBUG_PAINT 1
133 //#define PROJ_DEBUG_NOSEAMBLEED 1
134 //#define PROJ_DEBUG_PRINT_CLIP 1
135 #define PROJ_DEBUG_WINCLIP 1
136
137
138 #ifndef PROJ_DEBUG_NOSEAMBLEED
139 /* projectFaceSeamFlags options */
140 //#define PROJ_FACE_IGNORE      (1<<0)  /* When the face is hidden, backfacing or occluded */
141 //#define PROJ_FACE_INIT        (1<<1)  /* When we have initialized the faces data */
142 #define PROJ_FACE_SEAM1 (1 << 0)  /* If this face has a seam on any of its edges */
143 #define PROJ_FACE_SEAM2 (1 << 1)
144 #define PROJ_FACE_SEAM3 (1 << 2)
145 #define PROJ_FACE_SEAM4 (1 << 3)
146
147 #define PROJ_FACE_NOSEAM1   (1 << 4)
148 #define PROJ_FACE_NOSEAM2   (1 << 5)
149 #define PROJ_FACE_NOSEAM3   (1 << 6)
150 #define PROJ_FACE_NOSEAM4   (1 << 7)
151
152 /* face winding */
153 #define PROJ_FACE_WINDING_INIT 1
154 #define PROJ_FACE_WINDING_CW 2
155
156 /* a slightly scaled down face is used to get fake 3D location for edge pixels in the seams
157  * as this number approaches  1.0f the likelihood increases of float precision errors where
158  * it is occluded by an adjacent face */
159 #define PROJ_FACE_SCALE_SEAM    0.99f
160 #endif  /* PROJ_DEBUG_NOSEAMBLEED */
161
162
163 #define PROJ_SRC_VIEW       1
164 #define PROJ_SRC_IMAGE_CAM  2
165 #define PROJ_SRC_IMAGE_VIEW 3
166 #define PROJ_SRC_VIEW_FILL  4
167
168 #define PROJ_VIEW_DATA_ID "view_data"
169 #define PROJ_VIEW_DATA_SIZE (4 * 4 + 4 * 4 + 3) /* viewmat + winmat + clipsta + clipend + is_ortho */
170
171 #define PROJ_BUCKET_NULL        0
172 #define PROJ_BUCKET_INIT        (1 << 0)
173 // #define PROJ_BUCKET_CLONE_INIT       (1<<1)
174
175 /* used for testing doubles, if a point is on a line etc */
176 #define PROJ_GEOM_TOLERANCE 0.00075f
177 #define PROJ_PIXEL_TOLERANCE 0.01f
178
179 /* vert flags */
180 #define PROJ_VERT_CULL 1
181
182 /* to avoid locking in tile initialization */
183 #define TILE_PENDING SET_INT_IN_POINTER(-1)
184
185 /* This is mainly a convenience struct used so we can keep an array of images we use
186  * Thir imbufs, etc, in 1 array, When using threads this array is copied for each thread
187  * because 'partRedrawRect' and 'touch' values would not be thread safe */
188 typedef struct ProjPaintImage {
189         Image *ima;
190         ImBuf *ibuf;
191         ImagePaintPartialRedraw *partRedrawRect;
192         volatile void **undoRect; /* only used to build undo tiles during painting */
193         unsigned short **maskRect; /* the mask accumulation must happen on canvas, not on space screen bucket.
194                                     * Here we store the mask rectangle */
195         bool **valid; /* store flag to enforce validation of undo rectangle */
196         bool touch;
197 } ProjPaintImage;
198
199 /* Main projection painting struct passed to all projection painting functions */
200 typedef struct ProjPaintState {
201         View3D *v3d;
202         RegionView3D *rv3d;
203         ARegion *ar;
204         Scene *scene;
205         int source; /* PROJ_SRC_**** */
206
207         /* the paint color. It can change depending of inverted mode or not */
208         float paint_color[3];
209         float paint_color_linear[3];
210         float dither;
211
212         Brush *brush;
213         short tool, blend, mode;
214         int orig_brush_size;
215         float brush_size;
216         Object *ob;
217         /* end similarities with ImagePaintState */
218
219         DerivedMesh    *dm;
220         int dm_totface;
221         int dm_totedge;
222         int dm_totvert;
223         int dm_release;
224
225         MVert          *dm_mvert;
226         MEdge          *dm_medge;
227         MFace          *dm_mface;
228         MTFace         **dm_mtface;
229         MTFace         **dm_mtface_clone;    /* other UV map, use for cloning between layers */
230         MTFace         *dm_mtface_stencil;
231
232         Image *stencil_ima;
233         Image *canvas_ima;
234         Image *clone_ima;
235         float stencil_value;
236
237         /* projection painting only */
238         MemArena *arena_mt[BLENDER_MAX_THREADS]; /* for multithreading, the first item is sometimes used for non threaded cases too */
239         LinkNode **bucketRect;              /* screen sized 2D array, each pixel has a linked list of ProjPixel's */
240         LinkNode **bucketFaces;             /* bucketRect aligned array linkList of faces overlapping each bucket */
241         unsigned char *bucketFlags;         /* store if the bucks have been initialized  */
242 #ifndef PROJ_DEBUG_NOSEAMBLEED
243         char *faceSeamFlags;                /* store info about faces, if they are initialized etc*/
244         char *faceWindingFlags;             /* save the winding of the face in uv space, helps as an extra validation step for seam detection */
245         float (*faceSeamUVs)[4][2];         /* expanded UVs for faces to use as seams */
246         LinkNode **vertFaces;               /* Only needed for when seam_bleed_px is enabled, use to find UV seams */
247 #endif
248         char *vertFlags;                    /* store options per vert, now only store if the vert is pointing away from the view */
249         int buckets_x;                      /* The size of the bucket grid, the grid span's screenMin/screenMax so you can paint outsize the screen or with 2 brushes at once */
250         int buckets_y;
251
252         ProjPaintImage *projImages;
253
254         int pixel_sizeof;           /* result of project_paint_pixel_sizeof(), constant per stroke */
255
256         int image_tot;              /* size of projectImages array */
257
258         float (*screenCoords)[4];   /* verts projected into floating point screen space */
259         float *cavities;            /* cavity amount for vertices */
260         float screenMin[2];         /* 2D bounds for mesh verts on the screen's plane (screenspace) */
261         float screenMax[2];
262         float screen_width;         /* Calculated from screenMin & screenMax */
263         float screen_height;
264         int winx, winy;             /* from the carea or from the projection render */
265
266         /* options for projection painting */
267         bool  do_layer_clone;
268         bool  do_layer_stencil;
269         bool  do_layer_stencil_inv;
270         bool  do_stencil_brush;
271         bool  do_material_slots;
272
273         bool  do_occlude;               /* Use raytraced occlusion? - ortherwise will paint right through to the back*/
274         bool  do_backfacecull;          /* ignore faces with normals pointing away, skips a lot of raycasts if your normals are correctly flipped */
275         bool  do_mask_normal;           /* mask out pixels based on their normals */
276         bool  do_mask_cavity;           /* mask out pixels based on cavity */
277         bool  do_new_shading_nodes;     /* cache BKE_scene_use_new_shading_nodes value */
278         float normal_angle;             /* what angle to mask at */
279         float normal_angle__cos;         /* cos(normal_angle), faster to compare */
280         float normal_angle_inner;
281         float normal_angle_inner__cos;
282         float normal_angle_range;       /* difference between normal_angle and normal_angle_inner, for easy access */
283
284         bool do_face_sel;               /* quick access to (me->editflag & ME_EDIT_PAINT_FACE_SEL) */
285         bool is_ortho;
286         bool is_flip_object;            /* the object is negative scaled */
287         bool do_masking;              /* use masking during painting. Some operations such as airbrush may disable */
288         bool is_texbrush;              /* only to avoid running  */
289         bool is_maskbrush;            /* mask brush is applied before masking */
290 #ifndef PROJ_DEBUG_NOSEAMBLEED
291         float seam_bleed_px;
292 #endif
293         /* clone vars */
294         float cloneOffset[2];
295
296         float projectMat[4][4];     /* Projection matrix, use for getting screen coords */
297         float viewDir[3];           /* View vector, use for do_backfacecull and for ray casting with an ortho viewport  */
298         float viewPos[3];           /* View location in object relative 3D space, so can compare to verts  */
299         float clipsta, clipend;
300
301         /* reproject vars */
302         Image *reproject_image;
303         ImBuf *reproject_ibuf;
304
305         /* threads */
306         int thread_tot;
307         int bucketMin[2];
308         int bucketMax[2];
309         int context_bucket_x, context_bucket_y; /* must lock threads while accessing these */
310
311         /* redraw */
312         bool need_redraw;
313
314         struct CurveMapping *cavity_curve;
315         BlurKernel *blurkernel;
316
317         SpinLock *tile_lock;
318 } ProjPaintState;
319
320 typedef union pixelPointer {
321         float *f_pt;            /* float buffer */
322         unsigned int *uint_pt; /* 2 ways to access a char buffer */
323         unsigned char *ch_pt;
324 } PixelPointer;
325
326 typedef union pixelStore {
327         unsigned char ch[4];
328         unsigned int uint;
329         float f[4];
330 } PixelStore;
331
332 typedef struct ProjPixel {
333         float projCoSS[2]; /* the floating point screen projection of this pixel */
334         float worldCoSS[3];
335
336         short x_px, y_px;
337
338         unsigned short image_index; /* if anyone wants to paint onto more than 65535 images they can bite me */
339         unsigned char bb_cell_index;
340
341         /* for various reasons we may want to mask out painting onto this pixel */
342         unsigned short mask;
343
344         /* Only used when the airbrush is disabled.
345          * Store the max mask value to avoid painting over an area with a lower opacity
346          * with an advantage that we can avoid touching the pixel at all, if the
347          * new mask value is lower then mask_accum */
348         unsigned short *mask_accum;
349
350         /* horrible hack, store tile valid flag pointer here to re-validate tiles used for anchored and drag-dot strokes */
351         bool *valid;
352
353         PixelPointer origColor;
354         PixelStore newColor;
355         PixelPointer pixel;
356 } ProjPixel;
357
358 typedef struct ProjPixelClone {
359         struct ProjPixel __pp;
360         PixelStore clonepx;
361 } ProjPixelClone;
362
363 /* undo tile pushing */
364 typedef struct {
365         SpinLock *lock;
366         bool masked;
367         unsigned short tile_width;
368         ImBuf **tmpibuf;
369         ProjPaintImage *pjima;
370 } TileInfo;
371
372
373 /* Finish projection painting structs */
374
375 static TexPaintSlot *project_paint_face_paint_slot(const ProjPaintState *ps, int face_index)
376 {
377         MFace *mf = ps->dm_mface + face_index;
378         Material *ma = ps->dm->mat[mf->mat_nr];
379         return ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
380 }
381
382 static Image *project_paint_face_paint_image(const ProjPaintState *ps, int face_index)
383 {
384         if (ps->do_stencil_brush) {
385                 return ps->stencil_ima;
386         }
387         else {
388                 MFace *mf = ps->dm_mface + face_index;
389                 Material *ma = ps->dm->mat[mf->mat_nr];
390                 TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
391                 return slot ? slot->ima : ps->canvas_ima;
392         }
393 }
394
395 static TexPaintSlot *project_paint_face_clone_slot(const ProjPaintState *ps, int face_index)
396 {
397         MFace *mf = ps->dm_mface + face_index;
398         Material *ma = ps->dm->mat[mf->mat_nr];
399         return ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
400 }
401
402 static Image *project_paint_face_clone_image(const ProjPaintState *ps, int face_index)
403 {
404         MFace *mf = ps->dm_mface + face_index;
405         Material *ma = ps->dm->mat[mf->mat_nr];
406         TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
407         return slot ? slot->ima : ps->clone_ima;
408 }
409
410 /* fast projection bucket array lookup, use the safe version for bound checking  */
411 static int project_bucket_offset(const ProjPaintState *ps, const float projCoSS[2])
412 {
413         /* If we were not dealing with screenspace 2D coords we could simple do...
414          * ps->bucketRect[x + (y*ps->buckets_y)] */
415
416         /* please explain?
417          * projCoSS[0] - ps->screenMin[0]   : zero origin
418          * ... / ps->screen_width           : range from 0.0 to 1.0
419          * ... * ps->buckets_x              : use as a bucket index
420          *
421          * Second multiplication does similar but for vertical offset
422          */
423         return ( (int)(((projCoSS[0] - ps->screenMin[0]) / ps->screen_width)  * ps->buckets_x)) +
424                (((int)(((projCoSS[1] - ps->screenMin[1]) / ps->screen_height) * ps->buckets_y)) * ps->buckets_x);
425 }
426
427 static int project_bucket_offset_safe(const ProjPaintState *ps, const float projCoSS[2])
428 {
429         int bucket_index = project_bucket_offset(ps, projCoSS);
430
431         if (bucket_index < 0 || bucket_index >= ps->buckets_x * ps->buckets_y) {
432                 return -1;
433         }
434         else {
435                 return bucket_index;
436         }
437 }
438
439 static float VecZDepthOrtho(
440         const float pt[2],
441         const float v1[3], const float v2[3], const float v3[3],
442         float w[3])
443 {
444         barycentric_weights_v2(v1, v2, v3, pt, w);
445         return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]);
446 }
447
448 static float VecZDepthPersp(
449         const float pt[2],
450         const float v1[4], const float v2[4], const float v3[4],
451         float w[3])
452 {
453         float wtot_inv, wtot;
454         float w_tmp[3];
455
456         barycentric_weights_v2_persp(v1, v2, v3, pt, w);
457         /* for the depth we need the weights to match what
458          * barycentric_weights_v2 would return, in this case its easiest just to
459          * undo the 4th axis division and make it unit-sum
460          *
461          * don't call barycentric_weights_v2() because our callers expect 'w'
462          * to be weighted from the perspective */
463         w_tmp[0] = w[0] * v1[3];
464         w_tmp[1] = w[1] * v2[3];
465         w_tmp[2] = w[2] * v3[3];
466
467         wtot = w_tmp[0] + w_tmp[1] + w_tmp[2];
468
469         if (wtot != 0.0f) {
470                 wtot_inv = 1.0f / wtot;
471
472                 w_tmp[0] = w_tmp[0] * wtot_inv;
473                 w_tmp[1] = w_tmp[1] * wtot_inv;
474                 w_tmp[2] = w_tmp[2] * wtot_inv;
475         }
476         else /* dummy values for zero area face */
477                 w_tmp[0] = w_tmp[1] = w_tmp[2] = 1.0f / 3.0f;
478         /* done mimicing barycentric_weights_v2() */
479
480         return (v1[2] * w_tmp[0]) + (v2[2] * w_tmp[1]) + (v3[2] * w_tmp[2]);
481 }
482
483
484 /* Return the top-most face index that the screen space coord 'pt' touches (or -1) */
485 static int project_paint_PickFace(
486         const ProjPaintState *ps, const float pt[2],
487         float w[3], int *r_side)
488 {
489         LinkNode *node;
490         float w_tmp[3];
491         const float *v1, *v2, *v3, *v4;
492         int bucket_index;
493         int face_index;
494         int best_side = -1;
495         int best_face_index = -1;
496         float z_depth_best = FLT_MAX, z_depth;
497         MFace *mf;
498
499         bucket_index = project_bucket_offset_safe(ps, pt);
500         if (bucket_index == -1)
501                 return -1;
502
503
504
505         /* we could return 0 for 1 face buckets, as long as this function assumes
506          * that the point its testing is only every originated from an existing face */
507
508         for (node = ps->bucketFaces[bucket_index]; node; node = node->next) {
509                 face_index = GET_INT_FROM_POINTER(node->link);
510                 mf = ps->dm_mface + face_index;
511
512                 v1 = ps->screenCoords[mf->v1];
513                 v2 = ps->screenCoords[mf->v2];
514                 v3 = ps->screenCoords[mf->v3];
515
516                 if (isect_point_tri_v2(pt, v1, v2, v3)) {
517                         if (ps->is_ortho) z_depth = VecZDepthOrtho(pt, v1, v2, v3, w_tmp);
518                         else z_depth = VecZDepthPersp(pt, v1, v2, v3, w_tmp);
519
520                         if (z_depth < z_depth_best) {
521                                 best_face_index = face_index;
522                                 best_side = 0;
523                                 z_depth_best = z_depth;
524                                 copy_v3_v3(w, w_tmp);
525                         }
526                 }
527                 else if (mf->v4) {
528                         v4 = ps->screenCoords[mf->v4];
529
530                         if (isect_point_tri_v2(pt, v1, v3, v4)) {
531                                 if (ps->is_ortho) z_depth = VecZDepthOrtho(pt, v1, v3, v4, w_tmp);
532                                 else z_depth = VecZDepthPersp(pt, v1, v3, v4, w_tmp);
533
534                                 if (z_depth < z_depth_best) {
535                                         best_face_index = face_index;
536                                         best_side = 1;
537                                         z_depth_best = z_depth;
538                                         copy_v3_v3(w, w_tmp);
539                                 }
540                         }
541                 }
542         }
543
544         *r_side = best_side;
545         return best_face_index; /* will be -1 or a valid face */
546 }
547
548 /* Converts a uv coord into a pixel location wrapping if the uv is outside 0-1 range */
549 static void uvco_to_wrapped_pxco(const float uv[2], int ibuf_x, int ibuf_y, float *x, float *y)
550 {
551         /* use */
552         *x = fmodf(uv[0], 1.0f);
553         *y = fmodf(uv[1], 1.0f);
554
555         if (*x < 0.0f) *x += 1.0f;
556         if (*y < 0.0f) *y += 1.0f;
557
558         *x = *x * ibuf_x - 0.5f;
559         *y = *y * ibuf_y - 0.5f;
560 }
561
562 /* Set the top-most face color that the screen space coord 'pt' touches (or return 0 if none touch) */
563 static bool project_paint_PickColor(
564         const ProjPaintState *ps, const float pt[2],
565         float *rgba_fp, unsigned char *rgba, const bool interp)
566 {
567         float w[3], uv[2];
568         int side;
569         int face_index;
570         MTFace *tf;
571         Image *ima;
572         ImBuf *ibuf;
573         int xi, yi;
574
575
576         face_index = project_paint_PickFace(ps, pt, w, &side);
577
578         if (face_index == -1)
579                 return 0;
580
581         tf = *(ps->dm_mtface + face_index);
582
583         if (side == 0) {
584                 interp_v2_v2v2v2(uv, tf->uv[0], tf->uv[1], tf->uv[2], w);
585         }
586         else { /* QUAD */
587                 interp_v2_v2v2v2(uv, tf->uv[0], tf->uv[2], tf->uv[3], w);
588         }
589
590         ima = project_paint_face_paint_image(ps, face_index);
591         ibuf = BKE_image_get_first_ibuf(ima); /* we must have got the imbuf before getting here */
592         if (!ibuf) return 0;
593
594         if (interp) {
595                 float x, y;
596                 uvco_to_wrapped_pxco(uv, ibuf->x, ibuf->y, &x, &y);
597
598                 if (ibuf->rect_float) {
599                         if (rgba_fp) {
600                                 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_fp, x, y);
601                         }
602                         else {
603                                 float rgba_tmp_f[4];
604                                 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_tmp_f, x, y);
605                                 premul_float_to_straight_uchar(rgba, rgba_tmp_f);
606                         }
607                 }
608                 else {
609                         if (rgba) {
610                                 bilinear_interpolation_color_wrap(ibuf, rgba, NULL, x, y);
611                         }
612                         else {
613                                 unsigned char rgba_tmp[4];
614                                 bilinear_interpolation_color_wrap(ibuf, rgba_tmp, NULL, x, y);
615                                 straight_uchar_to_premul_float(rgba_fp, rgba_tmp);
616                         }
617                 }
618         }
619         else {
620                 //xi = (int)((uv[0]*ibuf->x) + 0.5f);
621                 //yi = (int)((uv[1]*ibuf->y) + 0.5f);
622                 //if (xi < 0 || xi >= ibuf->x  ||  yi < 0 || yi >= ibuf->y) return 0;
623
624                 /* wrap */
625                 xi = mod_i((int)(uv[0] * ibuf->x), ibuf->x);
626                 yi = mod_i((int)(uv[1] * ibuf->y), ibuf->y);
627
628                 if (rgba) {
629                         if (ibuf->rect_float) {
630                                 const float *rgba_tmp_fp = ibuf->rect_float + (xi + yi * ibuf->x * 4);
631                                 premul_float_to_straight_uchar(rgba, rgba_tmp_fp);
632                         }
633                         else {
634                                 *((unsigned int *)rgba) = *(unsigned int *)(((char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4));
635                         }
636                 }
637
638                 if (rgba_fp) {
639                         if (ibuf->rect_float) {
640                                 copy_v4_v4(rgba_fp, (ibuf->rect_float + ((xi + yi * ibuf->x) * 4)));
641                         }
642                         else {
643                                 unsigned char *tmp_ch = ((unsigned char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4);
644                                 straight_uchar_to_premul_float(rgba_fp, tmp_ch);
645                         }
646                 }
647         }
648         BKE_image_release_ibuf(ima, ibuf, NULL);
649         return 1;
650 }
651
652 /* Check if 'pt' is infront of the 3 verts on the Z axis (used for screenspace occlusuion test)
653  * return...
654  *  0   : no occlusion
655  * -1   : no occlusion but 2D intersection is true (avoid testing the other half of a quad)
656  *  1   : occluded
657  *  2   : occluded with w[3] weights set (need to know in some cases) */
658
659 static int project_paint_occlude_ptv(
660         const float pt[3],
661         const float v1[4], const float v2[4], const float v3[4],
662         float w[3], const bool is_ortho)
663 {
664         /* if all are behind us, return false */
665         if (v1[2] > pt[2] && v2[2] > pt[2] && v3[2] > pt[2])
666                 return 0;
667
668         /* do a 2D point in try intersection */
669         if (!isect_point_tri_v2(pt, v1, v2, v3))
670                 return 0;  /* we know there is  */
671
672
673         /* From here on we know there IS an intersection */
674         /* if ALL of the verts are infront of us then we know it intersects ? */
675         if (v1[2] < pt[2] && v2[2] < pt[2] && v3[2] < pt[2]) {
676                 return 1;
677         }
678         else {
679                 /* we intersect? - find the exact depth at the point of intersection */
680                 /* Is this point is occluded by another face? */
681                 if (is_ortho) {
682                         if (VecZDepthOrtho(pt, v1, v2, v3, w) < pt[2]) return 2;
683                 }
684                 else {
685                         if (VecZDepthPersp(pt, v1, v2, v3, w) < pt[2]) return 2;
686                 }
687         }
688         return -1;
689 }
690
691
692 static int project_paint_occlude_ptv_clip(
693         const ProjPaintState *ps, const MFace *mf,
694         const float pt[3], const float v1[4], const float v2[4], const float v3[4],
695         const int side)
696 {
697         float w[3], wco[3];
698         int ret = project_paint_occlude_ptv(pt, v1, v2, v3, w, ps->is_ortho);
699
700         if (ret <= 0)
701                 return ret;
702
703         if (ret == 1) { /* weights not calculated */
704                 if (ps->is_ortho) barycentric_weights_v2(v1, v2, v3, pt, w);
705                 else barycentric_weights_v2_persp(v1, v2, v3, pt, w);
706         }
707
708         /* Test if we're in the clipped area, */
709         if (side) interp_v3_v3v3v3(wco, ps->dm_mvert[mf->v1].co, ps->dm_mvert[mf->v3].co, ps->dm_mvert[mf->v4].co, w);
710         else interp_v3_v3v3v3(wco, ps->dm_mvert[mf->v1].co, ps->dm_mvert[mf->v2].co, ps->dm_mvert[mf->v3].co, w);
711
712         if (!ED_view3d_clipping_test(ps->rv3d, wco, true)) {
713                 return 1;
714         }
715
716         return -1;
717 }
718
719
720 /* Check if a screenspace location is occluded by any other faces
721  * check, pixelScreenCo must be in screenspace, its Z-Depth only needs to be used for comparison
722  * and doesn't need to be correct in relation to X and Y coords (this is the case in perspective view) */
723 static bool project_bucket_point_occluded(
724         const ProjPaintState *ps, LinkNode *bucketFace,
725         const int orig_face, const float pixelScreenCo[4])
726 {
727         MFace *mf;
728         int face_index;
729         int isect_ret;
730         float w[3]; /* not needed when clipping */
731         const bool do_clip = ps->rv3d ? (ps->rv3d->rflag & RV3D_CLIPPING) != 0 : 0;
732
733         /* we could return 0 for 1 face buckets, as long as this function assumes
734          * that the point its testing is only every originated from an existing face */
735
736         for (; bucketFace; bucketFace = bucketFace->next) {
737                 face_index = GET_INT_FROM_POINTER(bucketFace->link);
738
739                 if (orig_face != face_index) {
740                         mf = ps->dm_mface + face_index;
741                         if (do_clip)
742                                 isect_ret = project_paint_occlude_ptv_clip(ps, mf, pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v2], ps->screenCoords[mf->v3], 0);
743                         else
744                                 isect_ret = project_paint_occlude_ptv(pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v2], ps->screenCoords[mf->v3], w, ps->is_ortho);
745
746                         /* Note, if (isect_ret == -1) then we don't want to test the other side of the quad */
747                         if (isect_ret == 0 && mf->v4) {
748                                 if (do_clip)
749                                         isect_ret = project_paint_occlude_ptv_clip(ps, mf, pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v3], ps->screenCoords[mf->v4], 1);
750                                 else
751                                         isect_ret = project_paint_occlude_ptv(pixelScreenCo, ps->screenCoords[mf->v1], ps->screenCoords[mf->v3], ps->screenCoords[mf->v4], w, ps->is_ortho);
752                         }
753                         if (isect_ret >= 1) {
754                                 /* TODO - we may want to cache the first hit,
755                                  * it is not possible to swap the face order in the list anymore */
756                                 return true;
757                         }
758                 }
759         }
760         return false;
761 }
762
763 /* basic line intersection, could move to math_geom.c, 2 points with a horiz line
764  * 1 for an intersection, 2 if the first point is aligned, 3 if the second point is aligned */
765 #define ISECT_TRUE 1
766 #define ISECT_TRUE_P1 2
767 #define ISECT_TRUE_P2 3
768 static int line_isect_y(const float p1[2], const float p2[2], const float y_level, float *x_isect)
769 {
770         float y_diff;
771
772         if (y_level == p1[1]) { /* are we touching the first point? - no interpolation needed */
773                 *x_isect = p1[0];
774                 return ISECT_TRUE_P1;
775         }
776         if (y_level == p2[1]) { /* are we touching the second point? - no interpolation needed */
777                 *x_isect = p2[0];
778                 return ISECT_TRUE_P2;
779         }
780
781         y_diff = fabsf(p1[1] - p2[1]); /* yuck, horizontal line, we cant do much here */
782
783         if (y_diff < 0.000001f) {
784                 *x_isect = (p1[0] + p2[0]) * 0.5f;
785                 return ISECT_TRUE;
786         }
787
788         if (p1[1] > y_level && p2[1] < y_level) {
789                 *x_isect = (p2[0] * (p1[1] - y_level) + p1[0] * (y_level - p2[1])) / y_diff;  /*(p1[1]-p2[1]);*/
790                 return ISECT_TRUE;
791         }
792         else if (p1[1] < y_level && p2[1] > y_level) {
793                 *x_isect = (p2[0] * (y_level - p1[1]) + p1[0] * (p2[1] - y_level)) / y_diff;  /*(p2[1]-p1[1]);*/
794                 return ISECT_TRUE;
795         }
796         else {
797                 return 0;
798         }
799 }
800
801 static int line_isect_x(const float p1[2], const float p2[2], const float x_level, float *y_isect)
802 {
803         float x_diff;
804
805         if (x_level == p1[0]) { /* are we touching the first point? - no interpolation needed */
806                 *y_isect = p1[1];
807                 return ISECT_TRUE_P1;
808         }
809         if (x_level == p2[0]) { /* are we touching the second point? - no interpolation needed */
810                 *y_isect = p2[1];
811                 return ISECT_TRUE_P2;
812         }
813
814         x_diff = fabsf(p1[0] - p2[0]); /* yuck, horizontal line, we cant do much here */
815
816         if (x_diff < 0.000001f) { /* yuck, vertical line, we cant do much here */
817                 *y_isect = (p1[0] + p2[0]) * 0.5f;
818                 return ISECT_TRUE;
819         }
820
821         if (p1[0] > x_level && p2[0] < x_level) {
822                 *y_isect = (p2[1] * (p1[0] - x_level) + p1[1] * (x_level - p2[0])) / x_diff; /*(p1[0]-p2[0]);*/
823                 return ISECT_TRUE;
824         }
825         else if (p1[0] < x_level && p2[0] > x_level) {
826                 *y_isect = (p2[1] * (x_level - p1[0]) + p1[1] * (p2[0] - x_level)) / x_diff; /*(p2[0]-p1[0]);*/
827                 return ISECT_TRUE;
828         }
829         else {
830                 return 0;
831         }
832 }
833
834 /* simple func use for comparing UV locations to check if there are seams.
835  * Its possible this gives incorrect results, when the UVs for 1 face go into the next
836  * tile, but do not do this for the adjacent face, it could return a false positive.
837  * This is so unlikely that Id not worry about it. */
838 #ifndef PROJ_DEBUG_NOSEAMBLEED
839 static bool cmp_uv(const float vec2a[2], const float vec2b[2])
840 {
841         /* if the UV's are not between 0.0 and 1.0 */
842         float xa = fmodf(vec2a[0], 1.0f);
843         float ya = fmodf(vec2a[1], 1.0f);
844
845         float xb = fmodf(vec2b[0], 1.0f);
846         float yb = fmodf(vec2b[1], 1.0f);
847
848         if (xa < 0.0f) xa += 1.0f;
849         if (ya < 0.0f) ya += 1.0f;
850
851         if (xb < 0.0f) xb += 1.0f;
852         if (yb < 0.0f) yb += 1.0f;
853
854         return ((fabsf(xa - xb) < PROJ_GEOM_TOLERANCE) && (fabsf(ya - yb) < PROJ_GEOM_TOLERANCE)) ? 1 : 0;
855 }
856 #endif
857
858 /* set min_px and max_px to the image space bounds of the UV coords
859  * return zero if there is no area in the returned rectangle */
860 #ifndef PROJ_DEBUG_NOSEAMBLEED
861 static bool pixel_bounds_uv(
862         const float uv1[2], const float uv2[2], const float uv3[2], const float uv4[2],
863         rcti *bounds_px,
864         const int ibuf_x, const int ibuf_y,
865         const bool is_quad
866         )
867 {
868         float min_uv[2], max_uv[2]; /* UV bounds */
869
870         INIT_MINMAX2(min_uv, max_uv);
871
872         minmax_v2v2_v2(min_uv, max_uv, uv1);
873         minmax_v2v2_v2(min_uv, max_uv, uv2);
874         minmax_v2v2_v2(min_uv, max_uv, uv3);
875         if (is_quad)
876                 minmax_v2v2_v2(min_uv, max_uv, uv4);
877
878         bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
879         bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
880
881         bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
882         bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
883
884         /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
885
886         /* face uses no UV area when quantized to pixels? */
887         return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
888 }
889 #endif
890
891 static bool pixel_bounds_array(float (*uv)[2], rcti *bounds_px, const int ibuf_x, const int ibuf_y, int tot)
892 {
893         float min_uv[2], max_uv[2]; /* UV bounds */
894
895         if (tot == 0) {
896                 return 0;
897         }
898
899         INIT_MINMAX2(min_uv, max_uv);
900
901         while (tot--) {
902                 minmax_v2v2_v2(min_uv, max_uv, (*uv));
903                 uv++;
904         }
905
906         bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
907         bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
908
909         bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
910         bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
911
912         /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
913
914         /* face uses no UV area when quantized to pixels? */
915         return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
916 }
917
918 #ifndef PROJ_DEBUG_NOSEAMBLEED
919
920 static void project_face_winding_init(const ProjPaintState *ps, const int face_index)
921 {
922         /* detect the winding of faces in uv space */
923         MTFace *tf = ps->dm_mtface[face_index];
924         float winding = cross_tri_v2(tf->uv[0], tf->uv[1], tf->uv[2]);
925
926         if (ps->dm_mface[face_index].v4)
927                 winding += cross_tri_v2(tf->uv[2], tf->uv[3], tf->uv[0]);
928
929         if (winding > 0)
930                 ps->faceWindingFlags[face_index] |= PROJ_FACE_WINDING_CW;
931
932         ps->faceWindingFlags[face_index] |= PROJ_FACE_WINDING_INIT;
933 }
934
935 /* This function returns 1 if this face has a seam along the 2 face-vert indices
936  * 'orig_i1_fidx' and 'orig_i2_fidx' */
937 static bool check_seam(
938         const ProjPaintState *ps,
939         const int orig_face, const int orig_i1_fidx, const int orig_i2_fidx,
940         int *other_face, int *orig_fidx)
941 {
942         LinkNode *node;
943         int face_index;
944         unsigned int i1, i2;
945         int i1_fidx = -1, i2_fidx = -1; /* index in face */
946         MFace *mf;
947         MTFace *tf;
948         const MFace *orig_mf = ps->dm_mface + orig_face;
949         const MTFace *orig_tf = ps->dm_mtface[orig_face];
950
951         /* vert indices from face vert order indices */
952         i1 = (*(&orig_mf->v1 + orig_i1_fidx));
953         i2 = (*(&orig_mf->v1 + orig_i2_fidx));
954
955         for (node = ps->vertFaces[i1]; node; node = node->next) {
956                 face_index = GET_INT_FROM_POINTER(node->link);
957
958                 if (face_index != orig_face) {
959                         mf = ps->dm_mface + face_index;
960                         /* could check if the 2 faces images match here,
961                          * but then there wouldn't be a way to return the opposite face's info */
962
963
964                         /* We need to know the order of the verts in the adjacent face
965                          * set the i1_fidx and i2_fidx to (0,1,2,3) */
966                         i1_fidx = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, i1);
967                         i2_fidx = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, i2);
968
969                         /* Only need to check if 'i2_fidx' is valid because we know i1_fidx is the same vert on both faces */
970                         if (i2_fidx != -1) {
971                                 Image *tpage = project_paint_face_paint_image(ps, face_index);
972                                 Image *orig_tpage = project_paint_face_paint_image(ps, orig_face);
973
974                                 BLI_assert(i1_fidx != -1);
975
976                                 /* This IS an adjacent face!, now lets check if the UVs are ok */
977                                 tf = ps->dm_mtface[face_index];
978
979                                 /* set up the other face */
980                                 *other_face = face_index;
981                                 
982                                 /* we check if difference is 1 here, else we might have a case of edge 2-0 or 3-0 for quads */
983                                 *orig_fidx = (i1_fidx < i2_fidx && (i2_fidx - i1_fidx == 1)) ? i1_fidx : i2_fidx;
984
985                                 /* initialize face winding if needed */
986                                 if ((ps->faceWindingFlags[face_index] & PROJ_FACE_WINDING_INIT) == 0)
987                                         project_face_winding_init(ps, face_index);
988
989                                 /* first test if they have the same image */
990                                 if ((orig_tpage == tpage) &&
991                                     cmp_uv(orig_tf->uv[orig_i1_fidx], tf->uv[i1_fidx]) &&
992                                     cmp_uv(orig_tf->uv[orig_i2_fidx], tf->uv[i2_fidx]))
993                                 {
994                                         /* if faces don't have the same winding in uv space,
995                                          * they are on the same side so edge is boundary */
996                                         if ((ps->faceWindingFlags[face_index] & PROJ_FACE_WINDING_CW) !=
997                                             (ps->faceWindingFlags[orig_face] & PROJ_FACE_WINDING_CW))
998                                         {
999                                                 return 1;
1000                                         }
1001
1002                                         // printf("SEAM (NONE)\n");
1003                                         return 0;
1004
1005                                 }
1006                                 else {
1007                                         // printf("SEAM (UV GAP)\n");
1008                                         return 1;
1009                                 }
1010                         }
1011                 }
1012         }
1013         // printf("SEAM (NO FACE)\n");
1014         *other_face = -1;
1015         return 1;
1016 }
1017
1018 #define SMALL_NUMBER  1.e-6f
1019 BLI_INLINE float shell_v2v2_normal_dir_to_dist(float n[2], float d[2])
1020 {
1021         const float angle_cos = (normalize_v2(n) < SMALL_NUMBER) ? fabsf(dot_v2v2(d, n)) : 0.0f;
1022         return (UNLIKELY(angle_cos < SMALL_NUMBER)) ? 1.0f : (1.0f / angle_cos);
1023 }
1024 #undef SMALL_NUMBER
1025
1026 /* Calculate outset UV's, this is not the same as simply scaling the UVs,
1027  * since the outset coords are a margin that keep an even distance from the original UV's,
1028  * note that the image aspect is taken into account */
1029 static void uv_image_outset(
1030         float (*orig_uv)[2], float (*outset_uv)[2], const float scaler,
1031         const int ibuf_x, const int ibuf_y, const bool is_quad, const bool cw)
1032 {
1033         float a1, a2, a3, a4 = 0.0f;
1034         float puv[4][2]; /* pixelspace uv's */
1035         float no1[2], no2[2], no3[2], no4[2]; /* normals */
1036         float dir1[2], dir2[2], dir3[2], dir4[2];
1037         float ibuf_inv[2];
1038
1039         ibuf_inv[0] = 1.0f / (float)ibuf_x;
1040         ibuf_inv[1] = 1.0f / (float)ibuf_y;
1041
1042         /* make UV's in pixel space so we can */
1043         puv[0][0] = orig_uv[0][0] * ibuf_x;
1044         puv[0][1] = orig_uv[0][1] * ibuf_y;
1045
1046         puv[1][0] = orig_uv[1][0] * ibuf_x;
1047         puv[1][1] = orig_uv[1][1] * ibuf_y;
1048
1049         puv[2][0] = orig_uv[2][0] * ibuf_x;
1050         puv[2][1] = orig_uv[2][1] * ibuf_y;
1051
1052         if (is_quad) {
1053                 puv[3][0] = orig_uv[3][0] * ibuf_x;
1054                 puv[3][1] = orig_uv[3][1] * ibuf_y;
1055         }
1056
1057         /* face edge directions */
1058         sub_v2_v2v2(dir1, puv[1], puv[0]);
1059         sub_v2_v2v2(dir2, puv[2], puv[1]);
1060         normalize_v2(dir1);
1061         normalize_v2(dir2);
1062
1063         if (is_quad) {
1064                 sub_v2_v2v2(dir3, puv[3], puv[2]);
1065                 sub_v2_v2v2(dir4, puv[0], puv[3]);
1066                 normalize_v2(dir3);
1067                 normalize_v2(dir4);
1068         }
1069         else {
1070                 sub_v2_v2v2(dir3, puv[0], puv[2]);
1071                 normalize_v2(dir3);
1072         }
1073
1074         if (is_quad) {
1075                 /* here we just use the orthonormality property (a1, a2) dot (a2, -a1) = 0
1076                  * to get normals from the edge directions based on the winding */
1077                 if (cw) {
1078                         no1[0] = -dir4[1] - dir1[1];
1079                         no1[1] = dir4[0] + dir1[0];
1080                         no2[0] = -dir1[1] - dir2[1];
1081                         no2[1] = dir1[0] + dir2[0];
1082                         no3[0] = -dir2[1] - dir3[1];
1083                         no3[1] = dir2[0] + dir3[0];
1084                         no4[0] = -dir3[1] - dir4[1];
1085                         no4[1] = dir3[0] + dir4[0];
1086                 }
1087                 else {
1088                         no1[0] = dir4[1] + dir1[1];
1089                         no1[1] = -dir4[0] - dir1[0];
1090                         no2[0] = dir1[1] + dir2[1];
1091                         no2[1] = -dir1[0] - dir2[0];
1092                         no3[0] = dir2[1] + dir3[1];
1093                         no3[1] = -dir2[0] - dir3[0];
1094                         no4[0] = dir3[1] + dir4[1];
1095                         no4[1] = -dir3[0] - dir4[0];
1096                 }
1097
1098                 a1 = shell_v2v2_normal_dir_to_dist(no1, dir4);
1099                 a2 = shell_v2v2_normal_dir_to_dist(no2, dir1);
1100                 a3 = shell_v2v2_normal_dir_to_dist(no3, dir2);
1101                 a4 = shell_v2v2_normal_dir_to_dist(no4, dir3);
1102
1103                 mul_v2_fl(no1, a1 * scaler);
1104                 mul_v2_fl(no2, a2 * scaler);
1105                 mul_v2_fl(no3, a3 * scaler);
1106                 mul_v2_fl(no4, a4 * scaler);
1107                 add_v2_v2v2(outset_uv[0], puv[0], no1);
1108                 add_v2_v2v2(outset_uv[1], puv[1], no2);
1109                 add_v2_v2v2(outset_uv[2], puv[2], no3);
1110                 add_v2_v2v2(outset_uv[3], puv[3], no4);
1111                 mul_v2_v2(outset_uv[0], ibuf_inv);
1112                 mul_v2_v2(outset_uv[1], ibuf_inv);
1113                 mul_v2_v2(outset_uv[2], ibuf_inv);
1114                 mul_v2_v2(outset_uv[3], ibuf_inv);
1115         }
1116         else {
1117                 if (cw) {
1118                         no1[0] = -dir3[1] - dir1[1];
1119                         no1[1] = dir3[0] + dir1[0];
1120                         no2[0] = -dir1[1] - dir2[1];
1121                         no2[1] = dir1[0] + dir2[0];
1122                         no3[0] = -dir2[1] - dir3[1];
1123                         no3[1] = dir2[0] + dir3[0];
1124                 }
1125                 else {
1126                         no1[0] = dir3[1] + dir1[1];
1127                         no1[1] = -dir3[0] - dir1[0];
1128                         no2[0] = dir1[1] + dir2[1];
1129                         no2[1] = -dir1[0] - dir2[0];
1130                         no3[0] = dir2[1] + dir3[1];
1131                         no3[1] = -dir2[0] - dir3[0];
1132                 }
1133
1134                 a1 = shell_v2v2_normal_dir_to_dist(no1, dir3);
1135                 a2 = shell_v2v2_normal_dir_to_dist(no2, dir1);
1136                 a3 = shell_v2v2_normal_dir_to_dist(no3, dir2);
1137
1138                 mul_v2_fl(no1, a1 * scaler);
1139                 mul_v2_fl(no2, a2 * scaler);
1140                 mul_v2_fl(no3, a3 * scaler);
1141                 add_v2_v2v2(outset_uv[0], puv[0], no1);
1142                 add_v2_v2v2(outset_uv[1], puv[1], no2);
1143                 add_v2_v2v2(outset_uv[2], puv[2], no3);
1144
1145                 mul_v2_v2(outset_uv[0], ibuf_inv);
1146                 mul_v2_v2(outset_uv[1], ibuf_inv);
1147                 mul_v2_v2(outset_uv[2], ibuf_inv);
1148         }
1149 }
1150
1151 /*
1152  * Be tricky with flags, first 4 bits are PROJ_FACE_SEAM1 to 4, last 4 bits are PROJ_FACE_NOSEAM1 to 4
1153  * 1<<i - where i is (0-3)
1154  *
1155  * If we're multithreadng, make sure threads are locked when this is called
1156  */
1157 static void project_face_seams_init(const ProjPaintState *ps, const int face_index, const int is_quad)
1158 {
1159         int other_face, other_fidx; /* vars for the other face, we also set its flag */
1160         int fidx1 = is_quad ? 3 : 2;
1161         int fidx2 = 0; /* next fidx in the face (0,1,2,3) -> (1,2,3,0) or (0,1,2) -> (1,2,0) for a tri */
1162
1163         /* initialize face winding if needed */
1164         if ((ps->faceWindingFlags[face_index] & PROJ_FACE_WINDING_INIT) == 0)
1165                 project_face_winding_init(ps, face_index);
1166
1167         do {
1168                 if ((ps->faceSeamFlags[face_index] & (1 << fidx1 | 16 << fidx1)) == 0) {
1169                         if (check_seam(ps, face_index, fidx1, fidx2, &other_face, &other_fidx)) {
1170                                 ps->faceSeamFlags[face_index] |= 1 << fidx1;
1171                                 if (other_face != -1)
1172                                         ps->faceSeamFlags[other_face] |= 1 << other_fidx;
1173                         }
1174                         else {
1175                                 ps->faceSeamFlags[face_index] |= 16 << fidx1;
1176                                 if (other_face != -1)
1177                                         ps->faceSeamFlags[other_face] |= 16 << other_fidx;  /* second 4 bits for disabled */
1178                         }
1179                 }
1180
1181                 fidx2 = fidx1;
1182         } while (fidx1--);
1183 }
1184 #endif // PROJ_DEBUG_NOSEAMBLEED
1185
1186
1187 /* Converts a UV location to a 3D screenspace location
1188  * Takes a 'uv' and 3 UV coords, and sets the values of pixelScreenCo
1189  *
1190  * This is used for finding a pixels location in screenspace for painting */
1191 static void screen_px_from_ortho(
1192         const float uv[2],
1193         const float v1co[3], const float v2co[3], const float v3co[3],  /* Screenspace coords */
1194         const float uv1co[2], const float uv2co[2], const float uv3co[2],
1195         float pixelScreenCo[4],
1196         float w[3])
1197 {
1198         barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1199         interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w);
1200 }
1201
1202 /* same as screen_px_from_ortho except we
1203  * do perspective correction on the pixel coordinate */
1204 static void screen_px_from_persp(
1205         const float uv[2],
1206         const float v1co[4], const float v2co[4], const float v3co[4],  /* screenspace coords */
1207         const float uv1co[2], const float uv2co[2], const float uv3co[2],
1208         float pixelScreenCo[4],
1209         float w[3])
1210 {
1211         float w_int[3];
1212         float wtot_inv, wtot;
1213         barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1214
1215         /* re-weight from the 4th coord of each screen vert */
1216         w_int[0] = w[0] * v1co[3];
1217         w_int[1] = w[1] * v2co[3];
1218         w_int[2] = w[2] * v3co[3];
1219
1220         wtot = w_int[0] + w_int[1] + w_int[2];
1221
1222         if (wtot > 0.0f) {
1223                 wtot_inv = 1.0f / wtot;
1224                 w_int[0] *= wtot_inv;
1225                 w_int[1] *= wtot_inv;
1226                 w_int[2] *= wtot_inv;
1227         }
1228         else {
1229                 w[0] = w[1] = w[2] =
1230                 w_int[0] = w_int[1] = w_int[2] = 1.0f / 3.0f;  /* dummy values for zero area face */
1231         }
1232         /* done re-weighting */
1233
1234         /* do interpolation based on projected weight */
1235         interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w_int);
1236 }
1237
1238
1239 static void project_face_pixel(
1240         const MTFace *tf_other, ImBuf *ibuf_other, const float w[3],
1241         bool side, unsigned char rgba_ub[4], float rgba_f[4])
1242 {
1243         const float *uvCo1, *uvCo2, *uvCo3;
1244         float uv_other[2], x, y;
1245
1246         uvCo1 =  tf_other->uv[0];
1247         if (side == 1) {
1248                 uvCo2 = tf_other->uv[2];
1249                 uvCo3 = tf_other->uv[3];
1250         }
1251         else {
1252                 uvCo2 =  tf_other->uv[1];
1253                 uvCo3 =  tf_other->uv[2];
1254         }
1255
1256         interp_v2_v2v2v2(uv_other, uvCo1, uvCo2, uvCo3, w);
1257
1258         /* use */
1259         uvco_to_wrapped_pxco(uv_other, ibuf_other->x, ibuf_other->y, &x, &y);
1260
1261
1262         if (ibuf_other->rect_float) { /* from float to float */
1263                 bilinear_interpolation_color_wrap(ibuf_other, NULL, rgba_f, x, y);
1264         }
1265         else { /* from char to float */
1266                 bilinear_interpolation_color_wrap(ibuf_other, rgba_ub, NULL, x, y);
1267         }
1268
1269 }
1270
1271 /* run this outside project_paint_uvpixel_init since pixels with mask 0 don't need init */
1272 static float project_paint_uvpixel_mask(
1273         const ProjPaintState *ps,
1274         const int face_index,
1275         const bool side,
1276         const float w[3])
1277 {
1278         float mask;
1279
1280         /* Image Mask */
1281         if (ps->do_layer_stencil) {
1282                 /* another UV maps image is masking this one's */
1283                 ImBuf *ibuf_other;
1284                 Image *other_tpage = ps->stencil_ima;
1285                 const MTFace *tf_other = ps->dm_mtface_stencil + face_index;
1286
1287                 if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1288                         /* BKE_image_acquire_ibuf - TODO - this may be slow */
1289                         unsigned char rgba_ub[4];
1290                         float rgba_f[4];
1291
1292                         project_face_pixel(tf_other, ibuf_other, w, side, rgba_ub, rgba_f);
1293
1294                         if (ibuf_other->rect_float) { /* from float to float */
1295                                 mask = ((rgba_f[0] + rgba_f[1] + rgba_f[2]) * (1.0f / 3.0f)) * rgba_f[3];
1296                         }
1297                         else { /* from char to float */
1298                                 mask = ((rgba_ub[0] + rgba_ub[1] + rgba_ub[2]) * (1.0f / (255.0f * 3.0f))) * (rgba_ub[3] * (1.0f / 255.0f));
1299                         }
1300
1301                         BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1302
1303                         if (!ps->do_layer_stencil_inv) /* matching the gimps layer mask black/white rules, white==full opacity */
1304                                 mask = (1.0f - mask);
1305
1306                         if (mask == 0.0f) {
1307                                 return 0.0f;
1308                         }
1309                 }
1310                 else {
1311                         return 0.0f;
1312                 }
1313         }
1314         else {
1315                 mask = 1.0f;
1316         }
1317
1318         if (ps->do_mask_cavity) {
1319                 MFace *mf = &ps->dm_mface[face_index];
1320                 float ca1, ca2, ca3, ca_mask;
1321                 ca1 = ps->cavities[mf->v1];
1322                 if (side == 1) {
1323                         ca2 = ps->cavities[mf->v3];
1324                         ca3 = ps->cavities[mf->v4];
1325                 }
1326                 else {
1327                         ca2 = ps->cavities[mf->v2];
1328                         ca3 = ps->cavities[mf->v3];
1329                 }
1330
1331                 ca_mask = w[0] * ca1 + w[1] * ca2 + w[2] * ca3;
1332                 ca_mask = curvemapping_evaluateF(ps->cavity_curve, 0, ca_mask);
1333                 CLAMP(ca_mask, 0.0f, 1.0f);
1334                 mask *= ca_mask;
1335         }
1336
1337         /* calculate mask */
1338         if (ps->do_mask_normal) {
1339                 MFace *mf = &ps->dm_mface[face_index];
1340                 float no[3], angle_cos;
1341                 if (mf->flag & ME_SMOOTH) {
1342                         const short *no1, *no2, *no3;
1343                         no1 = ps->dm_mvert[mf->v1].no;
1344                         if (side == 1) {
1345                                 no2 = ps->dm_mvert[mf->v3].no;
1346                                 no3 = ps->dm_mvert[mf->v4].no;
1347                         }
1348                         else {
1349                                 no2 = ps->dm_mvert[mf->v2].no;
1350                                 no3 = ps->dm_mvert[mf->v3].no;
1351                         }
1352
1353                         no[0] = w[0] * no1[0] + w[1] * no2[0] + w[2] * no3[0];
1354                         no[1] = w[0] * no1[1] + w[1] * no2[1] + w[2] * no3[1];
1355                         no[2] = w[0] * no1[2] + w[1] * no2[2] + w[2] * no3[2];
1356                         normalize_v3(no);
1357                 }
1358                 else {
1359                         /* incase the */
1360 #if 1
1361                         /* normalizing per pixel isn't optimal, we could cache or check ps->*/
1362                         if (mf->v4)
1363                                 normal_quad_v3(no,
1364                                                ps->dm_mvert[mf->v1].co,
1365                                                ps->dm_mvert[mf->v2].co,
1366                                                ps->dm_mvert[mf->v3].co,
1367                                                ps->dm_mvert[mf->v4].co);
1368                         else
1369                                 normal_tri_v3(no,
1370                                               ps->dm_mvert[mf->v1].co,
1371                                               ps->dm_mvert[mf->v2].co,
1372                                               ps->dm_mvert[mf->v3].co);
1373 #else
1374                         /* don't use because some modifiers dont have normal data (subsurf for eg) */
1375                         copy_v3_v3(no, (float *)ps->dm->getTessFaceData(ps->dm, face_index, CD_NORMAL));
1376 #endif
1377                 }
1378
1379                 if (UNLIKELY(ps->is_flip_object)) {
1380                         negate_v3(no);
1381                 }
1382
1383                 /* now we can use the normal as a mask */
1384                 if (ps->is_ortho) {
1385                         angle_cos = dot_v3v3(ps->viewDir, no);
1386                 }
1387                 else {
1388                         /* Annoying but for the perspective view we need to get the pixels location in 3D space :/ */
1389                         float viewDirPersp[3];
1390                         const float *co1, *co2, *co3;
1391                         co1 = ps->dm_mvert[mf->v1].co;
1392                         if (side == 1) {
1393                                 co2 = ps->dm_mvert[mf->v3].co;
1394                                 co3 = ps->dm_mvert[mf->v4].co;
1395                         }
1396                         else {
1397                                 co2 = ps->dm_mvert[mf->v2].co;
1398                                 co3 = ps->dm_mvert[mf->v3].co;
1399                         }
1400
1401                         /* Get the direction from the viewPoint to the pixel and normalize */
1402                         viewDirPersp[0] = (ps->viewPos[0] - (w[0] * co1[0] + w[1] * co2[0] + w[2] * co3[0]));
1403                         viewDirPersp[1] = (ps->viewPos[1] - (w[0] * co1[1] + w[1] * co2[1] + w[2] * co3[1]));
1404                         viewDirPersp[2] = (ps->viewPos[2] - (w[0] * co1[2] + w[1] * co2[2] + w[2] * co3[2]));
1405                         normalize_v3(viewDirPersp);
1406                         if (UNLIKELY(ps->is_flip_object)) {
1407                                 negate_v3(viewDirPersp);
1408                         }
1409
1410                         angle_cos = dot_v3v3(viewDirPersp, no);
1411                 }
1412
1413                 if (angle_cos <= ps->normal_angle__cos) {
1414                         return 0.0f; /* outsize the normal limit*/
1415                 }
1416                 else if (angle_cos < ps->normal_angle_inner__cos) {
1417                         mask *= (ps->normal_angle - acosf(angle_cos)) / ps->normal_angle_range;
1418                 } /* otherwise no mask normal is needed, were within the limit */
1419         }
1420
1421         /* This only works when the opacity dosnt change while painting, stylus pressure messes with this
1422          * so don't use it. */
1423         // if (ps->is_airbrush == 0) mask *= BKE_brush_alpha_get(ps->brush);
1424
1425         return mask;
1426 }
1427
1428 static int project_paint_pixel_sizeof(const short tool)
1429 {
1430         if ((tool == PAINT_TOOL_CLONE) || (tool == PAINT_TOOL_SMEAR)) {
1431                 return sizeof(ProjPixelClone);
1432         }
1433         else {
1434                 return sizeof(ProjPixel);
1435         }
1436 }
1437
1438 static int project_paint_undo_subtiles(const TileInfo *tinf, int tx, int ty)
1439 {
1440         ProjPaintImage *pjIma = tinf->pjima;
1441         int tile_index = tx + ty * tinf->tile_width;
1442         bool generate_tile = false;
1443
1444         /* double check lock to avoid locking */
1445         if (UNLIKELY(!pjIma->undoRect[tile_index])) {
1446                 if (tinf->lock)
1447                         BLI_spin_lock(tinf->lock);
1448                 if (LIKELY(!pjIma->undoRect[tile_index])) {
1449                         pjIma->undoRect[tile_index] = TILE_PENDING;
1450                         generate_tile = true;
1451                 }
1452                 if (tinf->lock)
1453                         BLI_spin_unlock(tinf->lock);
1454         }
1455
1456
1457         if (generate_tile) {
1458                 volatile void *undorect;
1459                 if (tinf->masked) {
1460                         undorect = image_undo_push_tile(pjIma->ima, pjIma->ibuf, tinf->tmpibuf, tx, ty, &pjIma->maskRect[tile_index], &pjIma->valid[tile_index], true);
1461                 }
1462                 else {
1463                         undorect = image_undo_push_tile(pjIma->ima, pjIma->ibuf, tinf->tmpibuf, tx, ty, NULL, &pjIma->valid[tile_index], true);
1464                 }
1465
1466                 pjIma->ibuf->userflags |= IB_BITMAPDIRTY;
1467                 /* tile ready, publish */
1468                 if (tinf->lock)
1469                         BLI_spin_lock(tinf->lock);
1470                 pjIma->undoRect[tile_index] = undorect;
1471                 if (tinf->lock)
1472                         BLI_spin_unlock(tinf->lock);
1473
1474         }
1475
1476         return tile_index;
1477 }
1478
1479 /* run this function when we know a bucket's, face's pixel can be initialized,
1480  * return the ProjPixel which is added to 'ps->bucketRect[bucket_index]' */
1481 static ProjPixel *project_paint_uvpixel_init(
1482         const ProjPaintState *ps,
1483         MemArena *arena,
1484         const TileInfo *tinf,
1485         int x_px, int y_px,
1486         const float mask,
1487         const int face_index,
1488         const float pixelScreenCo[4],
1489         const float world_spaceCo[3],
1490         const bool side,
1491         const float w[3])
1492 {
1493         ProjPixel *projPixel;
1494         int x_tile, y_tile;
1495         int x_round, y_round;
1496         int tile_offset;
1497         /* volatile is important here to ensure pending check is not optimized away by compiler*/
1498         volatile int tile_index;
1499
1500         ProjPaintImage *projima = tinf->pjima;
1501         ImBuf *ibuf = projima->ibuf;
1502         /* wrap pixel location */
1503
1504         x_px = mod_i(x_px, ibuf->x);
1505         y_px = mod_i(y_px, ibuf->y);
1506
1507         BLI_assert(ps->pixel_sizeof == project_paint_pixel_sizeof(ps->tool));
1508         projPixel = BLI_memarena_alloc(arena, ps->pixel_sizeof);
1509
1510         /* calculate the undo tile offset of the pixel, used to store the original
1511          * pixel color and accumulated mask if any */
1512         x_tile =  x_px >> IMAPAINT_TILE_BITS;
1513         y_tile =  y_px >> IMAPAINT_TILE_BITS;
1514
1515         x_round = x_tile * IMAPAINT_TILE_SIZE;
1516         y_round = y_tile * IMAPAINT_TILE_SIZE;
1517         //memset(projPixel, 0, size);
1518
1519         tile_offset = (x_px - x_round) + (y_px - y_round) * IMAPAINT_TILE_SIZE;
1520         tile_index = project_paint_undo_subtiles(tinf, x_tile, y_tile);
1521
1522         /* other thread may be initializing the tile so wait here */
1523         while (projima->undoRect[tile_index] == TILE_PENDING)
1524                 ;
1525
1526         BLI_assert(tile_index < (IMAPAINT_TILE_NUMBER(ibuf->x) * IMAPAINT_TILE_NUMBER(ibuf->y)));
1527         BLI_assert(tile_offset < (IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE));
1528
1529         projPixel->valid = projima->valid[tile_index];
1530
1531         if (ibuf->rect_float) {
1532                 projPixel->pixel.f_pt = ibuf->rect_float + ((x_px + y_px * ibuf->x) * 4);
1533                 projPixel->origColor.f_pt = (float *)projima->undoRect[tile_index] + 4 * tile_offset;
1534                 zero_v4(projPixel->newColor.f);
1535         }
1536         else {
1537                 projPixel->pixel.ch_pt = (unsigned char *)(ibuf->rect + (x_px + y_px * ibuf->x));
1538                 projPixel->origColor.uint_pt = (unsigned int *)projima->undoRect[tile_index] + tile_offset;
1539                 projPixel->newColor.uint = 0;
1540         }
1541
1542         /* screenspace unclamped, we could keep its z and w values but don't need them at the moment */
1543         if (ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
1544                 copy_v3_v3(projPixel->worldCoSS, world_spaceCo);
1545         }
1546
1547         copy_v2_v2(projPixel->projCoSS, pixelScreenCo);
1548
1549         projPixel->x_px = x_px;
1550         projPixel->y_px = y_px;
1551
1552         projPixel->mask = (unsigned short)(mask * 65535);
1553         if (ps->do_masking)
1554                 projPixel->mask_accum = projima->maskRect[tile_index] + tile_offset;
1555         else
1556                 projPixel->mask_accum = NULL;
1557
1558         /* which bounding box cell are we in?, needed for undo */
1559         projPixel->bb_cell_index = ((int)(((float)x_px / (float)ibuf->x) * PROJ_BOUNDBOX_DIV)) +
1560                                    ((int)(((float)y_px / (float)ibuf->y) * PROJ_BOUNDBOX_DIV)) * PROJ_BOUNDBOX_DIV;
1561
1562         /* done with view3d_project_float inline */
1563         if (ps->tool == PAINT_TOOL_CLONE) {
1564                 if (ps->dm_mtface_clone) {
1565                         ImBuf *ibuf_other;
1566                         Image *other_tpage = project_paint_face_clone_image(ps, face_index);
1567                         const MTFace *tf_other = ps->dm_mtface_clone[face_index];
1568
1569                         if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1570                                 /* BKE_image_acquire_ibuf - TODO - this may be slow */
1571
1572                                 if (ibuf->rect_float) {
1573                                         if (ibuf_other->rect_float) { /* from float to float */
1574                                                 project_face_pixel(tf_other, ibuf_other, w, side, NULL, ((ProjPixelClone *)projPixel)->clonepx.f);
1575                                         }
1576                                         else { /* from char to float */
1577                                                 unsigned char rgba_ub[4];
1578                                                 float rgba[4];
1579                                                 project_face_pixel(tf_other, ibuf_other, w, side, rgba_ub, NULL);
1580                                                 srgb_to_linearrgb_uchar4(rgba, rgba_ub);
1581                                                 straight_to_premul_v4_v4(((ProjPixelClone *)projPixel)->clonepx.f, rgba);
1582                                         }
1583                                 }
1584                                 else {
1585                                         if (ibuf_other->rect_float) { /* float to char */
1586                                                 float rgba[4];
1587                                                 project_face_pixel(tf_other, ibuf_other, w, side, NULL, rgba);
1588                                                 premul_to_straight_v4(rgba);
1589                                                 linearrgb_to_srgb_uchar3(((ProjPixelClone *)projPixel)->clonepx.ch, rgba);
1590                                                 ((ProjPixelClone *)projPixel)->clonepx.ch[3] =  rgba[3] * 255;
1591                                         }
1592                                         else { /* char to char */
1593                                                 project_face_pixel(tf_other, ibuf_other, w, side, ((ProjPixelClone *)projPixel)->clonepx.ch, NULL);
1594                                         }
1595                                 }
1596
1597                                 BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1598                         }
1599                         else {
1600                                 if (ibuf->rect_float) {
1601                                         ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0;
1602                                 }
1603                                 else {
1604                                         ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0;
1605                                 }
1606                         }
1607
1608                 }
1609                 else {
1610                         float co[2];
1611                         sub_v2_v2v2(co, projPixel->projCoSS, ps->cloneOffset);
1612
1613                         /* no need to initialize the bucket, we're only checking buckets faces and for this
1614                          * the faces are already initialized in project_paint_delayed_face_init(...) */
1615                         if (ibuf->rect_float) {
1616                                 if (!project_paint_PickColor(ps, co, ((ProjPixelClone *)projPixel)->clonepx.f, NULL, 1)) {
1617                                         ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0; /* zero alpha - ignore */
1618                                 }
1619                         }
1620                         else {
1621                                 if (!project_paint_PickColor(ps, co, NULL, ((ProjPixelClone *)projPixel)->clonepx.ch, 1)) {
1622                                         ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0; /* zero alpha - ignore */
1623                                 }
1624                         }
1625                 }
1626         }
1627
1628 #ifdef PROJ_DEBUG_PAINT
1629         if (ibuf->rect_float) projPixel->pixel.f_pt[0] = 0;
1630         else                  projPixel->pixel.ch_pt[0] = 0;
1631 #endif
1632         /* pointer arithmetics */
1633         projPixel->image_index = projima - ps->projImages;
1634
1635         return projPixel;
1636 }
1637
1638 static bool line_clip_rect2f(
1639         const rctf *rect,
1640         const float l1[2], const float l2[2],
1641         float l1_clip[2], float l2_clip[2])
1642 {
1643         /* first account for horizontal, then vertical lines */
1644         /* horiz */
1645         if (fabsf(l1[1] - l2[1]) < PROJ_GEOM_TOLERANCE) {
1646                 /* is the line out of range on its Y axis? */
1647                 if (l1[1] < rect->ymin || l1[1] > rect->ymax) {
1648                         return 0;
1649                 }
1650                 /* line is out of range on its X axis */
1651                 if ((l1[0] < rect->xmin && l2[0] < rect->xmin) || (l1[0] > rect->xmax && l2[0] > rect->xmax)) {
1652                         return 0;
1653                 }
1654
1655
1656                 if (fabsf(l1[0] - l2[0]) < PROJ_GEOM_TOLERANCE) { /* this is a single point  (or close to)*/
1657                         if (BLI_rctf_isect_pt_v(rect, l1)) {
1658                                 copy_v2_v2(l1_clip, l1);
1659                                 copy_v2_v2(l2_clip, l2);
1660                                 return 1;
1661                         }
1662                         else {
1663                                 return 0;
1664                         }
1665                 }
1666
1667                 copy_v2_v2(l1_clip, l1);
1668                 copy_v2_v2(l2_clip, l2);
1669                 CLAMP(l1_clip[0], rect->xmin, rect->xmax);
1670                 CLAMP(l2_clip[0], rect->xmin, rect->xmax);
1671                 return 1;
1672         }
1673         else if (fabsf(l1[0] - l2[0]) < PROJ_GEOM_TOLERANCE) {
1674                 /* is the line out of range on its X axis? */
1675                 if (l1[0] < rect->xmin || l1[0] > rect->xmax) {
1676                         return 0;
1677                 }
1678
1679                 /* line is out of range on its Y axis */
1680                 if ((l1[1] < rect->ymin && l2[1] < rect->ymin) || (l1[1] > rect->ymax && l2[1] > rect->ymax)) {
1681                         return 0;
1682                 }
1683
1684                 if (fabsf(l1[1] - l2[1]) < PROJ_GEOM_TOLERANCE) { /* this is a single point  (or close to)*/
1685                         if (BLI_rctf_isect_pt_v(rect, l1)) {
1686                                 copy_v2_v2(l1_clip, l1);
1687                                 copy_v2_v2(l2_clip, l2);
1688                                 return 1;
1689                         }
1690                         else {
1691                                 return 0;
1692                         }
1693                 }
1694
1695                 copy_v2_v2(l1_clip, l1);
1696                 copy_v2_v2(l2_clip, l2);
1697                 CLAMP(l1_clip[1], rect->ymin, rect->ymax);
1698                 CLAMP(l2_clip[1], rect->ymin, rect->ymax);
1699                 return 1;
1700         }
1701         else {
1702                 float isect;
1703                 short ok1 = 0;
1704                 short ok2 = 0;
1705
1706                 /* Done with vertical lines */
1707
1708                 /* are either of the points inside the rectangle ? */
1709                 if (BLI_rctf_isect_pt_v(rect, l1)) {
1710                         copy_v2_v2(l1_clip, l1);
1711                         ok1 = 1;
1712                 }
1713
1714                 if (BLI_rctf_isect_pt_v(rect, l2)) {
1715                         copy_v2_v2(l2_clip, l2);
1716                         ok2 = 1;
1717                 }
1718
1719                 /* line inside rect */
1720                 if (ok1 && ok2) return 1;
1721
1722                 /* top/bottom */
1723                 if (line_isect_y(l1, l2, rect->ymin, &isect) && (isect >= rect->xmin) && (isect <= rect->xmax)) {
1724                         if (l1[1] < l2[1]) { /* line 1 is outside */
1725                                 l1_clip[0] = isect;
1726                                 l1_clip[1] = rect->ymin;
1727                                 ok1 = 1;
1728                         }
1729                         else {
1730                                 l2_clip[0] = isect;
1731                                 l2_clip[1] = rect->ymin;
1732                                 ok2 = 2;
1733                         }
1734                 }
1735
1736                 if (ok1 && ok2) return 1;
1737
1738                 if (line_isect_y(l1, l2, rect->ymax, &isect) && (isect >= rect->xmin) && (isect <= rect->xmax)) {
1739                         if (l1[1] > l2[1]) { /* line 1 is outside */
1740                                 l1_clip[0] = isect;
1741                                 l1_clip[1] = rect->ymax;
1742                                 ok1 = 1;
1743                         }
1744                         else {
1745                                 l2_clip[0] = isect;
1746                                 l2_clip[1] = rect->ymax;
1747                                 ok2 = 2;
1748                         }
1749                 }
1750
1751                 if (ok1 && ok2) return 1;
1752
1753                 /* left/right */
1754                 if (line_isect_x(l1, l2, rect->xmin, &isect) && (isect >= rect->ymin) && (isect <= rect->ymax)) {
1755                         if (l1[0] < l2[0]) { /* line 1 is outside */
1756                                 l1_clip[0] = rect->xmin;
1757                                 l1_clip[1] = isect;
1758                                 ok1 = 1;
1759                         }
1760                         else {
1761                                 l2_clip[0] = rect->xmin;
1762                                 l2_clip[1] = isect;
1763                                 ok2 = 2;
1764                         }
1765                 }
1766
1767                 if (ok1 && ok2) return 1;
1768
1769                 if (line_isect_x(l1, l2, rect->xmax, &isect) && (isect >= rect->ymin) && (isect <= rect->ymax)) {
1770                         if (l1[0] > l2[0]) { /* line 1 is outside */
1771                                 l1_clip[0] = rect->xmax;
1772                                 l1_clip[1] = isect;
1773                                 ok1 = 1;
1774                         }
1775                         else {
1776                                 l2_clip[0] = rect->xmax;
1777                                 l2_clip[1] = isect;
1778                                 ok2 = 2;
1779                         }
1780                 }
1781
1782                 if (ok1 && ok2) {
1783                         return 1;
1784                 }
1785                 else {
1786                         return 0;
1787                 }
1788         }
1789 }
1790
1791
1792
1793 /* scale the quad & tri about its center
1794  * scaling by PROJ_FACE_SCALE_SEAM (0.99x) is used for getting fake UV pixel coords that are on the
1795  * edge of the face but slightly inside it occlusion tests don't return hits on adjacent faces */
1796 #ifndef PROJ_DEBUG_NOSEAMBLEED
1797 static void scale_quad(float insetCos[4][3], float *origCos[4], const float inset)
1798 {
1799         float cent[3];
1800         cent[0] = (origCos[0][0] + origCos[1][0] + origCos[2][0] + origCos[3][0]) * (1.0f / 4.0f);
1801         cent[1] = (origCos[0][1] + origCos[1][1] + origCos[2][1] + origCos[3][1]) * (1.0f / 4.0f);
1802         cent[2] = (origCos[0][2] + origCos[1][2] + origCos[2][2] + origCos[3][2]) * (1.0f / 4.0f);
1803
1804         sub_v3_v3v3(insetCos[0], origCos[0], cent);
1805         sub_v3_v3v3(insetCos[1], origCos[1], cent);
1806         sub_v3_v3v3(insetCos[2], origCos[2], cent);
1807         sub_v3_v3v3(insetCos[3], origCos[3], cent);
1808
1809         mul_v3_fl(insetCos[0], inset);
1810         mul_v3_fl(insetCos[1], inset);
1811         mul_v3_fl(insetCos[2], inset);
1812         mul_v3_fl(insetCos[3], inset);
1813
1814         add_v3_v3(insetCos[0], cent);
1815         add_v3_v3(insetCos[1], cent);
1816         add_v3_v3(insetCos[2], cent);
1817         add_v3_v3(insetCos[3], cent);
1818 }
1819
1820
1821 static void scale_tri(float insetCos[4][3], float *origCos[4], const float inset)
1822 {
1823         float cent[3];
1824         cent[0] = (origCos[0][0] + origCos[1][0] + origCos[2][0]) * (1.0f / 3.0f);
1825         cent[1] = (origCos[0][1] + origCos[1][1] + origCos[2][1]) * (1.0f / 3.0f);
1826         cent[2] = (origCos[0][2] + origCos[1][2] + origCos[2][2]) * (1.0f / 3.0f);
1827
1828         sub_v3_v3v3(insetCos[0], origCos[0], cent);
1829         sub_v3_v3v3(insetCos[1], origCos[1], cent);
1830         sub_v3_v3v3(insetCos[2], origCos[2], cent);
1831
1832         mul_v3_fl(insetCos[0], inset);
1833         mul_v3_fl(insetCos[1], inset);
1834         mul_v3_fl(insetCos[2], inset);
1835
1836         add_v3_v3(insetCos[0], cent);
1837         add_v3_v3(insetCos[1], cent);
1838         add_v3_v3(insetCos[2], cent);
1839 }
1840 #endif //PROJ_DEBUG_NOSEAMBLEED
1841
1842 static float len_squared_v2v2_alt(const float v1[2], const float v2_1, const float v2_2)
1843 {
1844         float x, y;
1845
1846         x = v1[0] - v2_1;
1847         y = v1[1] - v2_2;
1848         return x * x + y * y;
1849 }
1850
1851 /* note, use a squared value so we can use len_squared_v2v2
1852  * be sure that you have done a bounds check first or this may fail */
1853 /* only give bucket_bounds as an arg because we need it elsewhere */
1854 static bool project_bucket_isect_circle(const float cent[2], const float radius_squared, const rctf *bucket_bounds)
1855 {
1856
1857         /* Would normally to a simple intersection test, however we know the bounds of these 2 already intersect
1858          * so we only need to test if the center is inside the vertical or horizontal bounds on either axis,
1859          * this is even less work then an intersection test
1860          */
1861 #if 0
1862         if (BLI_rctf_isect_pt_v(bucket_bounds, cent))
1863                 return 1;
1864 #endif
1865
1866         if ((bucket_bounds->xmin <= cent[0] && bucket_bounds->xmax >= cent[0]) ||
1867             (bucket_bounds->ymin <= cent[1] && bucket_bounds->ymax >= cent[1]))
1868         {
1869                 return 1;
1870         }
1871
1872         /* out of bounds left */
1873         if (cent[0] < bucket_bounds->xmin) {
1874                 /* lower left out of radius test */
1875                 if (cent[1] < bucket_bounds->ymin) {
1876                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
1877                 }
1878                 /* top left test */
1879                 else if (cent[1] > bucket_bounds->ymax) {
1880                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
1881                 }
1882         }
1883         else if (cent[0] > bucket_bounds->xmax) {
1884                 /* lower right out of radius test */
1885                 if (cent[1] < bucket_bounds->ymin) {
1886                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
1887                 }
1888                 /* top right test */
1889                 else if (cent[1] > bucket_bounds->ymax) {
1890                         return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
1891                 }
1892         }
1893
1894         return 0;
1895 }
1896
1897
1898
1899 /* Note for rect_to_uvspace_ortho() and rect_to_uvspace_persp()
1900  * in ortho view this function gives good results when bucket_bounds are outside the triangle
1901  * however in some cases, perspective view will mess up with faces that have minimal screenspace area
1902  * (viewed from the side)
1903  *
1904  * for this reason its not reliable in this case so we'll use the Simple Barycentric'
1905  * funcs that only account for points inside the triangle.
1906  * however switching back to this for ortho is always an option */
1907
1908 static void rect_to_uvspace_ortho(
1909         const rctf *bucket_bounds,
1910         const float *v1coSS, const float *v2coSS, const float *v3coSS,
1911         const float *uv1co, const float *uv2co, const float *uv3co,
1912         float bucket_bounds_uv[4][2],
1913         const int flip)
1914 {
1915         float uv[2];
1916         float w[3];
1917
1918         /* get the UV space bounding box */
1919         uv[0] = bucket_bounds->xmax;
1920         uv[1] = bucket_bounds->ymin;
1921         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
1922         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
1923
1924         //uv[0] = bucket_bounds->xmax; // set above
1925         uv[1] = bucket_bounds->ymax;
1926         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
1927         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
1928
1929         uv[0] = bucket_bounds->xmin;
1930         //uv[1] = bucket_bounds->ymax; // set above
1931         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
1932         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
1933
1934         //uv[0] = bucket_bounds->xmin; // set above
1935         uv[1] = bucket_bounds->ymin;
1936         barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
1937         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
1938 }
1939
1940 /* same as above but use barycentric_weights_v2_persp */
1941 static void rect_to_uvspace_persp(
1942         const rctf *bucket_bounds,
1943         const float *v1coSS, const float *v2coSS, const float *v3coSS,
1944         const float *uv1co, const float *uv2co, const float *uv3co,
1945         float bucket_bounds_uv[4][2],
1946         const int flip
1947         )
1948 {
1949         float uv[2];
1950         float w[3];
1951
1952         /* get the UV space bounding box */
1953         uv[0] = bucket_bounds->xmax;
1954         uv[1] = bucket_bounds->ymin;
1955         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
1956         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
1957
1958         //uv[0] = bucket_bounds->xmax; // set above
1959         uv[1] = bucket_bounds->ymax;
1960         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
1961         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
1962
1963         uv[0] = bucket_bounds->xmin;
1964         //uv[1] = bucket_bounds->ymax; // set above
1965         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
1966         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
1967
1968         //uv[0] = bucket_bounds->xmin; // set above
1969         uv[1] = bucket_bounds->ymin;
1970         barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
1971         interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
1972 }
1973
1974 /* This works as we need it to but we can save a few steps and not use it */
1975
1976 #if 0
1977 static float angle_2d_clockwise(const float p1[2], const float p2[2], const float p3[2])
1978 {
1979         float v1[2], v2[2];
1980
1981         v1[0] = p1[0] - p2[0];    v1[1] = p1[1] - p2[1];
1982         v2[0] = p3[0] - p2[0];    v2[1] = p3[1] - p2[1];
1983
1984         return -atan2f(v1[0] * v2[1] - v1[1] * v2[0], v1[0] * v2[0] + v1[1] * v2[1]);
1985 }
1986 #endif
1987
1988 #define ISECT_1 (1)
1989 #define ISECT_2 (1 << 1)
1990 #define ISECT_3 (1 << 2)
1991 #define ISECT_4 (1 << 3)
1992 #define ISECT_ALL3 ((1 << 3) - 1)
1993 #define ISECT_ALL4 ((1 << 4) - 1)
1994
1995 /* limit must be a fraction over 1.0f */
1996 static bool IsectPT2Df_limit(
1997         const float pt[2],
1998         const float v1[2], const float v2[2], const float v3[2],
1999         const float limit)
2000 {
2001         return ((area_tri_v2(pt, v1, v2) +
2002                  area_tri_v2(pt, v2, v3) +
2003                  area_tri_v2(pt, v3, v1)) / (area_tri_v2(v1, v2, v3))) < limit;
2004 }
2005
2006 /* Clip the face by a bucket and set the uv-space bucket_bounds_uv
2007  * so we have the clipped UV's to do pixel intersection tests with
2008  * */
2009 static int float_z_sort_flip(const void *p1, const void *p2)
2010 {
2011         return (((float *)p1)[2] < ((float *)p2)[2] ? 1 : -1);
2012 }
2013
2014 static int float_z_sort(const void *p1, const void *p2)
2015 {
2016         return (((float *)p1)[2] < ((float *)p2)[2] ? -1 : 1);
2017 }
2018
2019 /* assumes one point is within the rectangle */
2020 static bool line_rect_clip(
2021         const rctf *rect,
2022         const float l1[4], const float l2[4],
2023         const float uv1[2], const float uv2[2],
2024         float uv[2], bool is_ortho)
2025 {
2026         float min = FLT_MAX, tmp;
2027         float xlen = l2[0] - l1[0];
2028         float ylen = l2[1] - l1[1];
2029
2030         /* 0.1 might seem too much, but remember, this is pixels! */
2031         if (xlen > 0.1f) {
2032                 if ((l1[0] - rect->xmin) * (l2[0] - rect->xmin) <= 0) {
2033                         tmp = rect->xmin;
2034                         min = min_ff((tmp - l1[0]) / xlen, min);
2035                 }
2036                 else if ((l1[0] - rect->xmax) * (l2[0] - rect->xmax) < 0) {
2037                         tmp = rect->xmax;
2038                         min = min_ff((tmp - l1[0]) / xlen, min);
2039                 }
2040         }
2041
2042         if (ylen > 0.1f) {
2043                 if ((l1[1] - rect->ymin) * (l2[1] - rect->ymin) <= 0) {
2044                         tmp = rect->ymin;
2045                         min = min_ff((tmp - l1[1]) / ylen, min);
2046                 }
2047                 else if ((l1[1] - rect->ymax) * (l2[1] - rect->ymax) < 0) {
2048                         tmp = rect->ymax;
2049                         min = min_ff((tmp - l1[1]) / ylen, min);
2050                 }
2051         }
2052
2053         if (min == FLT_MAX)
2054                 return false;
2055
2056         tmp = (is_ortho) ? 1.0f : (l1[3] + min * (l2[3] - l1[3]));
2057
2058         uv[0] = (uv1[0] + min / tmp * (uv2[0] - uv1[0]));
2059         uv[1] = (uv1[1] + min / tmp * (uv2[1] - uv1[1]));
2060
2061         return true;
2062 }
2063
2064
2065 static void project_bucket_clip_face(
2066         const bool is_ortho, const bool is_flip_object,
2067         const rctf *bucket_bounds,
2068         const float *v1coSS, const float *v2coSS, const float *v3coSS,
2069         const float *uv1co, const float *uv2co, const float *uv3co,
2070         float bucket_bounds_uv[8][2],
2071         int *tot, bool cull)
2072 {
2073         int inside_bucket_flag = 0;
2074         int inside_face_flag = 0;
2075         int flip;
2076         bool colinear = false;
2077         
2078         float bucket_bounds_ss[4][2];
2079
2080         /* detect pathological case where face the three vertices are almost colinear in screen space.
2081          * mostly those will be culled but when flood filling or with smooth shading it's a possibility */
2082         if (dist_squared_to_line_v2(v1coSS, v2coSS, v3coSS) < 0.5f ||
2083             dist_squared_to_line_v2(v2coSS, v3coSS, v1coSS) < 0.5f)
2084         {
2085                 colinear = true;
2086         }
2087         
2088         /* get the UV space bounding box */
2089         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v1coSS);
2090         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v2coSS) << 1;
2091         inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v3coSS) << 2;
2092         
2093         if (inside_bucket_flag == ISECT_ALL3) {
2094                 /* is_flip_object is used here because we use the face winding */
2095                 flip = (((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) != is_flip_object) !=
2096                         (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2097
2098                 /* all screenspace points are inside the bucket bounding box,
2099                  * this means we don't need to clip and can simply return the UVs */
2100                 if (flip) { /* facing the back? */
2101                         copy_v2_v2(bucket_bounds_uv[0], uv3co);
2102                         copy_v2_v2(bucket_bounds_uv[1], uv2co);
2103                         copy_v2_v2(bucket_bounds_uv[2], uv1co);
2104                 }
2105                 else {
2106                         copy_v2_v2(bucket_bounds_uv[0], uv1co);
2107                         copy_v2_v2(bucket_bounds_uv[1], uv2co);
2108                         copy_v2_v2(bucket_bounds_uv[2], uv3co);
2109                 }               
2110                 
2111                 *tot = 3;
2112                 return;
2113         }
2114         /* handle pathological case here, no need for further intersections below since tringle area is almost zero */
2115         if (colinear) {
2116                 int flag;
2117                 
2118                 (*tot) = 0;
2119
2120                 if (cull)
2121                         return;
2122                 
2123                 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++; }
2124
2125                 flag = inside_bucket_flag & (ISECT_1 | ISECT_2);
2126                 if (flag && flag != (ISECT_1 | ISECT_2)) {
2127                         if (line_rect_clip(bucket_bounds, v1coSS, v2coSS, uv1co, uv2co, bucket_bounds_uv[*tot], is_ortho))
2128                                 (*tot)++;
2129                 }
2130                 
2131                 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++; }
2132                 
2133                 flag = inside_bucket_flag & (ISECT_2 | ISECT_3);
2134                 if (flag && flag != (ISECT_2 | ISECT_3)) {
2135                         if (line_rect_clip(bucket_bounds, v2coSS, v3coSS, uv2co, uv3co, bucket_bounds_uv[*tot], is_ortho))
2136                                 (*tot)++;
2137                 }
2138
2139                 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++; }
2140
2141                 flag = inside_bucket_flag & (ISECT_3 | ISECT_1);
2142                 if (flag && flag != (ISECT_3 | ISECT_1)) {
2143                         if (line_rect_clip(bucket_bounds, v3coSS, v1coSS, uv3co, uv1co, bucket_bounds_uv[*tot], is_ortho))
2144                                 (*tot)++;
2145                 }
2146                 
2147                 if ((*tot) < 3) {
2148                         /* no intersections to speak of, but more probable is that all face is just outside the
2149                          * rectangle and culled due to float precision issues. Since above teste have failed,
2150                          * just dump triangle as is for painting */
2151                         *tot = 0;
2152                         copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++;
2153                         copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++;
2154                         copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++;
2155                         return;
2156                 }
2157
2158                 return;
2159         }
2160
2161         /* get the UV space bounding box */
2162         /* use IsectPT2Df_limit here so we catch points are are touching the tri edge (or a small fraction over) */
2163         bucket_bounds_ss[0][0] = bucket_bounds->xmax;
2164         bucket_bounds_ss[0][1] = bucket_bounds->ymin;
2165         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[0], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_1 : 0);
2166
2167         bucket_bounds_ss[1][0] = bucket_bounds->xmax;
2168         bucket_bounds_ss[1][1] = bucket_bounds->ymax;
2169         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[1], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_2 : 0);
2170
2171         bucket_bounds_ss[2][0] = bucket_bounds->xmin;
2172         bucket_bounds_ss[2][1] = bucket_bounds->ymax;
2173         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[2], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_3 : 0);
2174
2175         bucket_bounds_ss[3][0] = bucket_bounds->xmin;
2176         bucket_bounds_ss[3][1] = bucket_bounds->ymin;
2177         inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[3], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_4 : 0);
2178
2179         flip = ((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) !=
2180                 (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2181
2182         if (inside_face_flag == ISECT_ALL4) {
2183                 /* bucket is totally inside the screenspace face, we can safely use weights */
2184
2185                 if (is_ortho) rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2186                 else rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2187
2188                 *tot = 4;
2189                 return;
2190         }
2191         else {
2192                 /* The Complicated Case!
2193                  *
2194                  * The 2 cases above are where the face is inside the bucket or the bucket is inside the face.
2195                  *
2196                  * we need to make a convex polyline from the intersection between the screenspace face
2197                  * and the bucket bounds.
2198                  *
2199                  * There are a number of ways this could be done, currently it just collects all intersecting verts,
2200                  * and line intersections,  then sorts them clockwise, this is a lot easier then evaluating the geometry to
2201                  * do a correct clipping on both shapes. */
2202
2203
2204                 /* add a bunch of points, we know must make up the convex hull which is the clipped rect and triangle */
2205
2206
2207
2208                 /* Maximum possible 6 intersections when using a rectangle and triangle */
2209                 float isectVCosSS[8][3]; /* The 3rd float is used to store angle for qsort(), NOT as a Z location */
2210                 float v1_clipSS[2], v2_clipSS[2];
2211                 float w[3];
2212
2213                 /* calc center */
2214                 float cent[2] = {0.0f, 0.0f};
2215                 /*float up[2] = {0.0f, 1.0f};*/
2216                 int i;
2217                 bool doubles;
2218
2219                 (*tot) = 0;
2220
2221                 if (inside_face_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[0]); (*tot)++; }
2222                 if (inside_face_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[1]); (*tot)++; }
2223                 if (inside_face_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[2]); (*tot)++; }
2224                 if (inside_face_flag & ISECT_4) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[3]); (*tot)++; }
2225
2226                 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], v1coSS); (*tot)++; }
2227                 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], v2coSS); (*tot)++; }
2228                 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], v3coSS); (*tot)++; }
2229
2230                 if ((inside_bucket_flag & (ISECT_1 | ISECT_2)) != (ISECT_1 | ISECT_2)) {
2231                         if (line_clip_rect2f(bucket_bounds, v1coSS, v2coSS, v1_clipSS, v2_clipSS)) {
2232                                 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2233                                 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2234                         }
2235                 }
2236
2237                 if ((inside_bucket_flag & (ISECT_2 | ISECT_3)) != (ISECT_2 | ISECT_3)) {
2238                         if (line_clip_rect2f(bucket_bounds, v2coSS, v3coSS, v1_clipSS, v2_clipSS)) {
2239                                 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2240                                 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2241                         }
2242                 }
2243
2244                 if ((inside_bucket_flag & (ISECT_3 | ISECT_1)) != (ISECT_3 | ISECT_1)) {
2245                         if (line_clip_rect2f(bucket_bounds, v3coSS, v1coSS, v1_clipSS, v2_clipSS)) {
2246                                 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2247                                 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2248                         }
2249                 }
2250
2251
2252                 if ((*tot) < 3) { /* no intersections to speak of */
2253                         *tot = 0;
2254                         return;
2255                 }
2256
2257                 /* now we have all points we need, collect their angles and sort them clockwise */
2258
2259                 for (i = 0; i < (*tot); i++) {
2260                         cent[0] += isectVCosSS[i][0];
2261                         cent[1] += isectVCosSS[i][1];
2262                 }
2263                 cent[0] = cent[0] / (float)(*tot);
2264                 cent[1] = cent[1] / (float)(*tot);
2265
2266
2267
2268                 /* Collect angles for every point around the center point */
2269
2270
2271 #if 0   /* uses a few more cycles then the above loop */
2272                 for (i = 0; i < (*tot); i++) {
2273                         isectVCosSS[i][2] = angle_2d_clockwise(up, cent, isectVCosSS[i]);
2274                 }
2275 #endif
2276
2277                 v1_clipSS[0] = cent[0]; /* Abuse this var for the loop below */
2278                 v1_clipSS[1] = cent[1] + 1.0f;
2279
2280                 for (i = 0; i < (*tot); i++) {
2281                         v2_clipSS[0] = isectVCosSS[i][0] - cent[0];
2282                         v2_clipSS[1] = isectVCosSS[i][1] - cent[1];
2283                         isectVCosSS[i][2] = atan2f(v1_clipSS[0] * v2_clipSS[1] - v1_clipSS[1] * v2_clipSS[0],
2284                                                    v1_clipSS[0] * v2_clipSS[0] + v1_clipSS[1] * v2_clipSS[1]);
2285                 }
2286
2287                 if (flip) qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort_flip);
2288                 else      qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort);
2289
2290                 doubles = true;
2291                 while (doubles == true) {
2292                         doubles = false;
2293
2294                         for (i = 0; i < (*tot); i++) {
2295                                 if (fabsf(isectVCosSS[(i + 1) % *tot][0] - isectVCosSS[i][0]) < PROJ_PIXEL_TOLERANCE &&
2296                                     fabsf(isectVCosSS[(i + 1) % *tot][1] - isectVCosSS[i][1]) < PROJ_PIXEL_TOLERANCE)
2297                                 {
2298                                         int j;
2299                                         for (j = i; j < (*tot) - 1; j++) {
2300                                                 isectVCosSS[j][0] = isectVCosSS[j + 1][0];
2301                                                 isectVCosSS[j][1] = isectVCosSS[j + 1][1];
2302                                         }
2303                                         doubles = true; /* keep looking for more doubles */
2304                                         (*tot)--;
2305                                 }
2306                         }
2307                         
2308                         /* its possible there is only a few left after remove doubles */
2309                         if ((*tot) < 3) {
2310                                 // printf("removed too many doubles B\n");
2311                                 *tot = 0;
2312                                 return;
2313                         }
2314                 }
2315
2316                 if (is_ortho) {
2317                         for (i = 0; i < (*tot); i++) {
2318                                 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2319                                 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2320                         }
2321                 }
2322                 else {
2323                         for (i = 0; i < (*tot); i++) {
2324                                 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2325                                 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2326                         }
2327                 }
2328         }
2329
2330 #ifdef PROJ_DEBUG_PRINT_CLIP
2331         /* include this at the bottom of the above function to debug the output */
2332
2333         {
2334                 /* If there are ever any problems, */
2335                 float test_uv[4][2];
2336                 int i;
2337                 if (is_ortho) rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2338                 else          rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2339                 printf("(  [(%f,%f), (%f,%f), (%f,%f), (%f,%f)], ",
2340                        test_uv[0][0], test_uv[0][1],   test_uv[1][0], test_uv[1][1],
2341                        test_uv[2][0], test_uv[2][1],    test_uv[3][0], test_uv[3][1]);
2342
2343                 printf("  [(%f,%f), (%f,%f), (%f,%f)], ", uv1co[0], uv1co[1],   uv2co[0], uv2co[1],    uv3co[0], uv3co[1]);
2344
2345                 printf("[");
2346                 for (i = 0; i < (*tot); i++) {
2347                         printf("(%f, %f),", bucket_bounds_uv[i][0], bucket_bounds_uv[i][1]);
2348                 }
2349                 printf("]),\\\n");
2350         }
2351 #endif
2352 }
2353
2354 /*
2355  * # This script creates faces in a blender scene from printed data above.
2356  *
2357  * project_ls = [
2358  * ...(output from above block)...
2359  * ]
2360  *
2361  * from Blender import Scene, Mesh, Window, sys, Mathutils
2362  *
2363  * import bpy
2364  *
2365  * V = Mathutils.Vector
2366  *
2367  * def main():
2368  *     sce = bpy.data.scenes.active
2369  *
2370  *     for item in project_ls:
2371  *         bb = item[0]
2372  *         uv = item[1]
2373  *         poly = item[2]
2374  *
2375  *         me = bpy.data.meshes.new()
2376  *         ob = sce.objects.new(me)
2377  *
2378  *         me.verts.extend([V(bb[0]).xyz, V(bb[1]).xyz, V(bb[2]).xyz, V(bb[3]).xyz])
2379  *         me.faces.extend([(0,1,2,3),])
2380  *         me.verts.extend([V(uv[0]).xyz, V(uv[1]).xyz, V(uv[2]).xyz])
2381  *         me.faces.extend([(4,5,6),])
2382  *
2383  *         vs = [V(p).xyz for p in poly]
2384  *         print len(vs)
2385  *         l = len(me.verts)
2386  *         me.verts.extend(vs)
2387  *
2388  *         i = l
2389  *         while i < len(me.verts):
2390  *             ii = i + 1
2391  *             if ii == len(me.verts):
2392  *                 ii = l
2393  *             me.edges.extend([i, ii])
2394  *             i += 1
2395  *
2396  * if __name__ == '__main__':
2397  *     main()
2398  */
2399
2400
2401 #undef ISECT_1
2402 #undef ISECT_2
2403 #undef ISECT_3
2404 #undef ISECT_4
2405 #undef ISECT_ALL3
2406 #undef ISECT_ALL4
2407
2408
2409 /* checks if pt is inside a convex 2D polyline, the polyline must be ordered rotating clockwise
2410  * otherwise it would have to test for mixed (line_point_side_v2 > 0.0f) cases */
2411 static bool IsectPoly2Df(const float pt[2], float uv[][2], const int tot)
2412 {
2413         int i;
2414         if (line_point_side_v2(uv[tot - 1], uv[0], pt) < 0.0f)
2415                 return 0;
2416
2417         for (i = 1; i < tot; i++) {
2418                 if (line_point_side_v2(uv[i - 1], uv[i], pt) < 0.0f)
2419                         return 0;
2420
2421         }
2422
2423         return 1;
2424 }
2425 static bool IsectPoly2Df_twoside(const float pt[2], float uv[][2], const int tot)
2426 {
2427         int i;
2428         bool side = (line_point_side_v2(uv[tot - 1], uv[0], pt) > 0.0f);
2429
2430         for (i = 1; i < tot; i++) {
2431                 if ((line_point_side_v2(uv[i - 1], uv[i], pt) > 0.0f) != side)
2432                         return 0;
2433
2434         }
2435
2436         return 1;
2437 }
2438
2439 /* One of the most important function for projection painting,
2440  * since it selects the pixels to be added into each bucket.
2441  *
2442  * initialize pixels from this face where it intersects with the bucket_index,
2443  * optionally initialize pixels for removing seams */
2444 static void project_paint_face_init(
2445         const ProjPaintState *ps,
2446         const int thread_index, const int bucket_index, const int face_index, const int image_index,
2447         const rctf *bucket_bounds, ImBuf *ibuf, ImBuf **tmpibuf,
2448         const bool clamp_u, const bool clamp_v)
2449 {
2450         /* Projection vars, to get the 3D locations into screen space  */
2451         MemArena *arena = ps->arena_mt[thread_index];
2452         LinkNode **bucketPixelNodes = ps->bucketRect + bucket_index;
2453         LinkNode *bucketFaceNodes = ps->bucketFaces[bucket_index];
2454         bool threaded = (ps->thread_tot > 1);
2455
2456         TileInfo tinf = {
2457                 ps->tile_lock,
2458                 ps->do_masking,
2459                 IMAPAINT_TILE_NUMBER(ibuf->x),
2460                 tmpibuf,
2461                 ps->projImages + image_index
2462         };
2463
2464         const MFace *mf = ps->dm_mface + face_index;
2465         const MTFace *tf = ps->dm_mtface[face_index];
2466
2467         /* UV/pixel seeking data */
2468         int x; /* Image X-Pixel */
2469         int y; /* Image Y-Pixel */
2470         float mask;
2471         float uv[2]; /* Image floating point UV - same as x, y but from 0.0-1.0 */
2472
2473         bool side;
2474         const float *v1coSS, *v2coSS, *v3coSS; /* vert co screen-space, these will be assigned to mf->v1,2,3 or mf->v1,3,4 */
2475
2476         float *vCo[4]; /* vertex screenspace coords */
2477
2478         float w[3], wco[3];
2479
2480         float *uv1co, *uv2co, *uv3co; /* for convenience only, these will be assigned to tf->uv[0],1,2 or tf->uv[0],2,3 */
2481         float pixelScreenCo[4];
2482         bool do_3d_mapping = ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D;
2483
2484         rcti bounds_px; /* ispace bounds */
2485         /* vars for getting uvspace bounds */
2486
2487         float tf_uv_pxoffset[4][2]; /* bucket bounds in UV space so we can init pixels only for this face,  */
2488         float xhalfpx, yhalfpx;
2489         const float ibuf_xf = (float)ibuf->x, ibuf_yf = (float)ibuf->y;
2490
2491         int has_x_isect = 0, has_isect = 0; /* for early loop exit */
2492
2493         int i1, i2, i3;
2494
2495         float uv_clip[8][2];
2496         int uv_clip_tot;
2497         const bool is_ortho = ps->is_ortho;
2498         const bool is_flip_object = ps->is_flip_object;
2499         const bool do_backfacecull = ps->do_backfacecull;
2500         const bool do_clip = ps->rv3d ? ps->rv3d->rflag & RV3D_CLIPPING : 0;
2501
2502         vCo[0] = ps->dm_mvert[mf->v1].co;
2503         vCo[1] = ps->dm_mvert[mf->v2].co;
2504         vCo[2] = ps->dm_mvert[mf->v3].co;
2505
2506
2507         /* Use tf_uv_pxoffset instead of tf->uv so we can offset the UV half a pixel
2508          * this is done so we can avoid offsetting all the pixels by 0.5 which causes
2509          * problems when wrapping negative coords */
2510         xhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 3.0f))) / ibuf_xf;
2511         yhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 4.0f))) / ibuf_yf;
2512
2513         /* Note about (PROJ_GEOM_TOLERANCE/x) above...
2514          * Needed to add this offset since UV coords are often quads aligned to pixels.
2515          * In this case pixels can be exactly between 2 triangles causing nasty
2516          * artifacts.
2517          *
2518          * This workaround can be removed and painting will still work on most cases
2519          * but since the first thing most people try is painting onto a quad- better make it work.
2520          */
2521
2522         tf_uv_pxoffset[0][0] = tf->uv[0][0] - xhalfpx;
2523         tf_uv_pxoffset[0][1] = tf->uv[0][1] - yhalfpx;
2524
2525         tf_uv_pxoffset[1][0] = tf->uv[1][0] - xhalfpx;
2526         tf_uv_pxoffset[1][1] = tf->uv[1][1] - yhalfpx;
2527
2528         tf_uv_pxoffset[2][0] = tf->uv[2][0] - xhalfpx;
2529         tf_uv_pxoffset[2][1] = tf->uv[2][1] - yhalfpx;
2530
2531         if (mf->v4) {
2532                 vCo[3] = ps->dm_mvert[mf->v4].co;
2533
2534                 tf_uv_pxoffset[3][0] = tf->uv[3][0] - xhalfpx;
2535                 tf_uv_pxoffset[3][1] = tf->uv[3][1] - yhalfpx;
2536                 side = 1;
2537         }
2538         else {
2539                 side = 0;
2540         }
2541
2542         do {
2543                 if (side == 1) {
2544                         i1 = 0; i2 = 2; i3 = 3;
2545                 }
2546                 else {
2547                         i1 = 0; i2 = 1; i3 = 2;
2548                 }
2549
2550                 uv1co = tf_uv_pxoffset[i1]; // was tf->uv[i1];
2551                 uv2co = tf_uv_pxoffset[i2]; // was tf->uv[i2];
2552                 uv3co = tf_uv_pxoffset[i3]; // was tf->uv[i3];
2553
2554                 v1coSS = ps->screenCoords[(*(&mf->v1 + i1))];
2555                 v2coSS = ps->screenCoords[(*(&mf->v1 + i2))];
2556                 v3coSS = ps->screenCoords[(*(&mf->v1 + i3))];
2557
2558                 /* This funtion gives is a concave polyline in UV space from the clipped quad and tri*/
2559                 project_bucket_clip_face(
2560                         is_ortho, is_flip_object,
2561                         bucket_bounds,
2562                         v1coSS, v2coSS, v3coSS,
2563                         uv1co, uv2co, uv3co,
2564                         uv_clip, &uv_clip_tot,
2565                         do_backfacecull || ps->do_occlude);
2566
2567                 /* sometimes this happens, better just allow for 8 intersectiosn even though there should be max 6 */
2568 #if 0
2569                 if (uv_clip_tot > 6) {
2570                         printf("this should never happen! %d\n", uv_clip_tot);
2571                 }
2572 #endif
2573
2574                 if (pixel_bounds_array(uv_clip, &bounds_px, ibuf->x, ibuf->y, uv_clip_tot)) {
2575
2576                         if (clamp_u) {
2577                                 CLAMP(bounds_px.xmin, 0, ibuf->x);
2578                                 CLAMP(bounds_px.xmax, 0, ibuf->x);
2579                         }
2580
2581                         if (clamp_v) {
2582                                 CLAMP(bounds_px.ymin, 0, ibuf->y);
2583                                 CLAMP(bounds_px.ymax, 0, ibuf->y);
2584                         }
2585
2586 #if 0
2587                         project_paint_undo_tiles_init(&bounds_px, ps->projImages + image_index, tmpibuf,
2588                                                       tile_width, threaded, ps->do_masking);
2589 #endif
2590                         /* clip face and */
2591
2592                         has_isect = 0;
2593                         for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2594                                 //uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2595                                 uv[1] = (float)y / ibuf_yf; /* use pixel offset UV coords instead */
2596
2597                                 has_x_isect = 0;
2598                                 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2599                                         //uv[0] = (((float)x) + 0.5f) / ibuf->x;
2600                                         uv[0] = (float)x / ibuf_xf; /* use pixel offset UV coords instead */
2601
2602                                         /* Note about IsectPoly2Df_twoside, checking the face or uv flipping doesnt work,
2603                                          * could check the poly direction but better to do this */
2604                                         if ((do_backfacecull == true  && IsectPoly2Df(uv, uv_clip, uv_clip_tot)) ||
2605                                             (do_backfacecull == false && IsectPoly2Df_twoside(uv, uv_clip, uv_clip_tot)))
2606                                         {
2607
2608                                                 has_x_isect = has_isect = 1;
2609
2610                                                 if (is_ortho) screen_px_from_ortho(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2611                                                 else screen_px_from_persp(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2612
2613                                                 /* a pity we need to get the worldspace pixel location here */
2614                                                 if (do_clip || do_3d_mapping) {
2615                                                         interp_v3_v3v3v3(wco, ps->dm_mvert[(*(&mf->v1 + i1))].co, ps->dm_mvert[(*(&mf->v1 + i2))].co, ps->dm_mvert[(*(&mf->v1 + i3))].co, w);
2616                                                         if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2617                                                                 continue; /* Watch out that no code below this needs to run */
2618                                                         }
2619                                                 }
2620
2621                                                 /* Is this UV visible from the view? - raytrace */
2622                                                 /* project_paint_PickFace is less complex, use for testing */
2623                                                 //if (project_paint_PickFace(ps, pixelScreenCo, w, &side) == face_index) {
2624                                                 if ((ps->do_occlude == false) ||
2625                                                     !project_bucket_point_occluded(ps, bucketFaceNodes, face_index, pixelScreenCo))
2626                                                 {
2627                                                         mask = project_paint_uvpixel_mask(ps, face_index, side, w);
2628
2629                                                         if (mask > 0.0f) {
2630                                                                 BLI_linklist_prepend_arena(
2631                                                                         bucketPixelNodes,
2632                                                                         project_paint_uvpixel_init(ps, arena, &tinf, x, y, mask, face_index,
2633                                                                                                    pixelScreenCo, wco, side, w),
2634                                                                         arena
2635                                                                         );
2636                                                         }
2637                                                 }
2638
2639                                         }
2640 //#if 0
2641                                         else if (has_x_isect) {
2642                                                 /* assuming the face is not a bow-tie - we know we cant intersect again on the X */
2643                                                 break;
2644                                         }
2645 //#endif
2646                                 }
2647
2648
2649 #if 0           /* TODO - investigate why this dosnt work sometimes! it should! */
2650                                 /* no intersection for this entire row, after some intersection above means we can quit now */
2651                                 if (has_x_isect == 0 && has_isect) {
2652                                         break;
2653                                 }
2654 #endif
2655                         }
2656                 }
2657         } while (side--);
2658
2659
2660
2661 #ifndef PROJ_DEBUG_NOSEAMBLEED
2662         if (ps->seam_bleed_px > 0.0f) {
2663                 int face_seam_flag;
2664
2665                 if (threaded)
2666                         BLI_lock_thread(LOCK_CUSTOM1);  /* Other threads could be modifying these vars */
2667
2668                 face_seam_flag = ps->faceSeamFlags[face_index];
2669
2670                 /* are any of our edges un-initialized? */
2671                 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_NOSEAM1)) == 0 ||
2672                     (face_seam_flag & (PROJ_FACE_SEAM2 | PROJ_FACE_NOSEAM2)) == 0 ||
2673                     (face_seam_flag & (PROJ_FACE_SEAM3 | PROJ_FACE_NOSEAM3)) == 0 ||
2674                     (face_seam_flag & (PROJ_FACE_SEAM4 | PROJ_FACE_NOSEAM4)) == 0)
2675                 {
2676                         project_face_seams_init(ps, face_index, mf->v4);
2677                         face_seam_flag = ps->faceSeamFlags[face_index];
2678                         //printf("seams - %d %d %d %d\n", flag&PROJ_FACE_SEAM1, flag&PROJ_FACE_SEAM2, flag&PROJ_FACE_SEAM3, flag&PROJ_FACE_SEAM4);
2679                 }
2680
2681                 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_SEAM2 | PROJ_FACE_SEAM3 | PROJ_FACE_SEAM4)) == 0) {
2682
2683                         if (threaded)
2684                                 BLI_unlock_thread(LOCK_CUSTOM1);  /* Other threads could be modifying these vars */
2685
2686                 }
2687                 else {
2688                         /* we have a seam - deal with it! */
2689
2690                         /* Now create new UV's for the seam face */
2691                         float (*outset_uv)[2] = ps->faceSeamUVs[face_index];
2692                         float insetCos[4][3]; /* inset face coords.  NOTE!!! ScreenSace for ortho, Worldspace in prespective view */
2693
2694                         float *vCoSS[4]; /* vertex screenspace coords */
2695
2696                         float bucket_clip_edges[2][2]; /* store the screenspace coords of the face, clipped by the bucket's screen aligned rectangle */
2697                         float edge_verts_inset_clip[2][3];
2698                         int fidx1, fidx2; /* face edge pairs - loop throuh these ((0,1), (1,2), (2,3), (3,0)) or ((0,1), (1,2), (2,0)) for a tri */
2699
2700                         float seam_subsection[4][2];
2701                         float fac1, fac2, ftot;
2702
2703                         if (outset_uv[0][0] == FLT_MAX) /* first time initialize */
2704                                 uv_image_outset(tf_uv_pxoffset, outset_uv, ps->seam_bleed_px, ibuf->x, ibuf->y, mf->v4 != 0, (ps->faceWindingFlags[face_index] & PROJ_FACE_WINDING_CW) == 0);
2705
2706                         /* ps->faceSeamUVs cant be modified when threading, now this is done we can unlock */
2707                         if (threaded)
2708                                 BLI_unlock_thread(LOCK_CUSTOM1);  /* Other threads could be modifying these vars */
2709
2710                         vCoSS[0] = ps->screenCoords[mf->v1];
2711                         vCoSS[1] = ps->screenCoords[mf->v2];
2712                         vCoSS[2] = ps->screenCoords[mf->v3];
2713                         if (mf->v4)
2714                                 vCoSS[3] = ps->screenCoords[mf->v4];
2715
2716                         /* PROJ_FACE_SCALE_SEAM must be slightly less then 1.0f */
2717                         if (is_ortho) {
2718                                 if (mf->v4) scale_quad(insetCos, vCoSS, PROJ_FACE_SCALE_SEAM);
2719                                 else        scale_tri(insetCos, vCoSS, PROJ_FACE_SCALE_SEAM);
2720                         }
2721                         else {
2722                                 if (mf->v4) scale_quad(insetCos, vCo, PROJ_FACE_SCALE_SEAM);
2723                                 else        scale_tri(insetCos, vCo, PROJ_FACE_SCALE_SEAM);
2724                         }
2725
2726                         side = 0; /* for triangles this wont need to change */
2727
2728                         for (fidx1 = 0; fidx1 < (mf->v4 ? 4 : 3); fidx1++) {
2729                                 if (mf->v4) fidx2 = (fidx1 == 3) ? 0 : fidx1 + 1;  /* next fidx in the face (0,1,2,3) -> (1,2,3,0) */
2730                                 else        fidx2 = (fidx1 == 2) ? 0 : fidx1 + 1;  /* next fidx in the face (0,1,2) -> (1,2,0) */
2731
2732                                 if ((face_seam_flag & (1 << fidx1)) && /* 1<<fidx1 -> PROJ_FACE_SEAM# */
2733                                     line_clip_rect2f(bucket_bounds, vCoSS[fidx1], vCoSS[fidx2], bucket_clip_edges[0], bucket_clip_edges[1]))
2734                                 {
2735
2736                                         ftot = len_v2v2(vCoSS[fidx1], vCoSS[fidx2]); /* screenspace edge length */
2737
2738                                         if (ftot > 0.0f) { /* avoid div by zero */
2739                                                 if (mf->v4) {
2740                                                         if (fidx1 == 2 || fidx2 == 2) side = 1;
2741                                                         else side = 0;
2742                                                 }
2743
2744                                                 fac1 = len_v2v2(vCoSS[fidx1], bucket_clip_edges[0]) / ftot;
2745                                                 fac2 = len_v2v2(vCoSS[fidx1], bucket_clip_edges[1]) / ftot;
2746
2747                                                 interp_v2_v2v2(seam_subsection[0], tf_uv_pxoffset[fidx1], tf_uv_pxoffset[fidx2], fac1);
2748                                                 interp_v2_v2v2(seam_subsection[1], tf_uv_pxoffset[fidx1], tf_uv_pxoffset[fidx2], fac2);
2749
2750                                                 interp_v2_v2v2(seam_subsection[2], outset_uv[fidx1], outset_uv[fidx2], fac2);
2751                                                 interp_v2_v2v2(seam_subsection[3], outset_uv[fidx1], outset_uv[fidx2], fac1);
2752
2753                                                 /* if the bucket_clip_edges values Z values was kept we could avoid this
2754                                                  * Inset needs to be added so occlusion tests wont hit adjacent faces */
2755                                                 interp_v3_v3v3(edge_verts_inset_clip[0], insetCos[fidx1], insetCos[fidx2], fac1);
2756                                                 interp_v3_v3v3(edge_verts_inset_clip[1], insetCos[fidx1], insetCos[fidx2], fac2);
2757
2758
2759                                                 if (pixel_bounds_uv(seam_subsection[0], seam_subsection[1], seam_subsection[2], seam_subsection[3], &bounds_px, ibuf->x, ibuf->y, true)) {
2760                                                         /* bounds between the seam rect and the uvspace bucket pixels */
2761
2762                                                         has_isect = 0;
2763                                                         for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2764                                                                 // uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2765                                                                 uv[1] = (float)y / ibuf_yf; /* use offset uvs instead */
2766
2767                                                                 has_x_isect = 0;
2768                                                                 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2769                                                                         //uv[0] = (((float)x) + 0.5f) / (float)ibuf->x;
2770                                                                         uv[0] = (float)x / ibuf_xf; /* use offset uvs instead */
2771
2772                                                                         /* test we're inside uvspace bucket and triangle bounds */
2773                                                                         if (isect_point_quad_v2(uv, seam_subsection[0], seam_subsection[1], seam_subsection[2], seam_subsection[3])) {
2774                                                                                 float fac;
2775
2776                                                                                 /* We need to find the closest point along the face edge,
2777                                                                                  * getting the screen_px_from_*** wont work because our actual location
2778                                                                                  * is not relevant, since we are outside the face, Use VecLerpf to find
2779                                                                                  * our location on the side of the face's UV */
2780 #if 0
2781                                                                                 if (is_ortho) screen_px_from_ortho(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2782                                                                                 else          screen_px_from_persp(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2783 #endif
2784
2785                                                                                 /* Since this is a seam we need to work out where on the line this pixel is */
2786                                                                                 //fac = line_point_factor_v2(uv, uv_seam_quad[0], uv_seam_quad[1]);
2787
2788                                                                                 fac = line_point_factor_v2(uv, seam_subsection[0], seam_subsection[1]);
2789                                                                                 if      (fac < 0.0f) { copy_v3_v3(pixelScreenCo, edge_verts_inset_clip[0]); }
2790                                                                                 else if (fac > 1.0f) { copy_v3_v3(pixelScreenCo, edge_verts_inset_clip[1]); }
2791                                                                                 else                 { interp_v3_v3v3(pixelScreenCo, edge_verts_inset_clip[0], edge_verts_inset_clip[1], fac); }
2792
2793                                                                                 if (!is_ortho) {
2794                                                                                         pixelScreenCo[3] = 1.0f;
2795                                                                                         mul_m4_v4((float(*)[4])ps->projectMat, pixelScreenCo); /* cast because of const */
2796                                                                                         pixelScreenCo[0] = (float)(ps->winx * 0.5f) + (ps->winx * 0.5f) * pixelScreenCo[0] / pixelScreenCo[3];
2797                                                                                         pixelScreenCo[1] = (float)(ps->winy * 0.5f) + (ps->winy * 0.5f) * pixelScreenCo[1] / pixelScreenCo[3];
2798                                                                                         pixelScreenCo[2] = pixelScreenCo[2] / pixelScreenCo[3]; /* Use the depth for bucket point occlusion */
2799                                                                                 }
2800
2801                                                                                 if ((ps->do_occlude == false) ||
2802                                                                                     !project_bucket_point_occluded(ps, bucketFaceNodes, face_index, pixelScreenCo))
2803                                                                                 {
2804                                                                                         /* Only bother calculating the weights if we intersect */
2805                                                                                         if (ps->do_mask_normal || ps->dm_mtface_clone) {
2806 #if 1
2807                                                                                                 /* get the UV on the line since we want to copy the pixels from there for bleeding */
2808                                                                                                 float uv_close[2];
2809                                                                                                 float uv_fac = closest_to_line_v2(uv_close, uv, tf_uv_pxoffset[fidx1], tf_uv_pxoffset[fidx2]);
2810                                                                                                 if      (uv_fac < 0.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx1]);
2811                                                                                                 else if (uv_fac > 1.0f) copy_v2_v2(uv_close, tf_uv_pxoffset[fidx2]);
2812
2813                                                                                                 if (side) {
2814                                                                                                         barycentric_weights_v2(tf_uv_pxoffset[0], tf_uv_pxoffset[2], tf_uv_pxoffset[3], uv_close, w);
2815                                                                                                 }
2816                                                                                                 else {
2817                                                                                                         barycentric_weights_v2(tf_uv_pxoffset[0], tf_uv_pxoffset[1], tf_uv_pxoffset[2], uv_close, w);
2818                                                                                                 }
2819 #else                                                                                   /* this is buggy with quads, don't use for now */
2820
2821                                                                                                 /* Cheat, we know where we are along the edge so work out the weights from that */
2822                                                                                                 uv_fac = fac1 + (uv_fac * (fac2 - fac1));
2823
2824                                                                                                 w[0] = w[1] = w[2] = 0.0;
2825                                                                                                 if (side) {
2826                                                                                                         w[fidx1 ? fidx1 - 1 : 0] = 1.0f - uv_fac;
2827                                                                                                         w[fidx2 ? fidx2 - 1 : 0] = uv_fac;
2828                                                                                                 }
2829                                                                                                 else {
2830                                                                                                         w[fidx1] = 1.0f - uv_fac;
2831                                                                                                         w[fidx2] = uv_fac;
2832                                                                                                 }
2833 #endif
2834                                                                                         }
2835
2836                                                                                         /* a pity we need to get the worldspace pixel location here */
2837                                                                                         if (do_clip || do_3d_mapping) {
2838                                                                                                 if (side) interp_v3_v3v3v3(wco, ps->dm_mvert[mf->v1].co, ps->dm_mvert[mf->v3].co, ps->dm_mvert[mf->v4].co, w);
2839                                                                                                 else      interp_v3_v3v3v3(wco, ps->dm_mvert[mf->v1].co, ps->dm_mvert[mf->v2].co, ps->dm_mvert[mf->v3].co, w);
2840
2841                                                                                                 if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2842                                                                                                         continue; /* Watch out that no code below this needs to run */
2843                                                                                                 }