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