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