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.
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.
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.
15 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
16 * All rights reserved.
18 * The Original Code is: some of this file.
21 /** \file blender/editors/sculpt_paint/paint_image_proj.c
23 * \brief Functions to paint images in 2D and 3D.
31 #include "MEM_guardedalloc.h"
34 # include "BLI_winstuff.h"
37 #include "BLI_blenlib.h"
38 #include "BLI_linklist.h"
40 #include "BLI_math_bits.h"
41 #include "BLI_math_color_blend.h"
42 #include "BLI_memarena.h"
43 #include "BLI_threads.h"
44 #include "BLI_utildefines.h"
46 #include "BLT_translation.h"
49 #include "IMB_imbuf.h"
50 #include "IMB_imbuf_types.h"
52 #include "DNA_brush_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_mesh_types.h"
55 #include "DNA_meshdata_types.h"
56 #include "DNA_node_types.h"
57 #include "DNA_object_types.h"
59 #include "BKE_brush.h"
60 #include "BKE_camera.h"
61 #include "BKE_colorband.h"
62 #include "BKE_context.h"
63 #include "BKE_colortools.h"
64 #include "BKE_idprop.h"
65 #include "BKE_image.h"
66 #include "BKE_library.h"
68 #include "BKE_material.h"
70 #include "BKE_mesh_mapping.h"
71 #include "BKE_mesh_runtime.h"
73 #include "BKE_paint.h"
74 #include "BKE_report.h"
75 #include "BKE_scene.h"
76 #include "BKE_screen.h"
77 #include "BKE_texture.h"
79 #include "DEG_depsgraph.h"
80 #include "DEG_depsgraph_query.h"
82 #include "UI_interface.h"
84 #include "ED_object.h"
88 #include "ED_screen.h"
89 #include "ED_uvedit.h"
90 #include "ED_view3d.h"
92 #include "GPU_extensions.h"
97 #include "RNA_access.h"
98 #include "RNA_define.h"
99 #include "RNA_enum_types.h"
101 #include "GPU_draw.h"
103 #include "IMB_colormanagement.h"
106 //#include "bmesh_tools.h"
108 #include "paint_intern.h"
110 static void partial_redraw_array_init(ImagePaintPartialRedraw *pr);
112 /* Defines and Structs */
113 /* unit_float_to_uchar_clamp as inline function */
114 BLI_INLINE unsigned char f_to_char(const float val)
116 return unit_float_to_uchar_clamp(val);
119 /* ProjectionPaint defines */
121 /* approx the number of buckets to have under the brush,
122 * used with the brush size to set the ps->buckets_x and ps->buckets_y value.
124 * When 3 - a brush should have ~9 buckets under it at once
125 * ...this helps for threading while painting as well as
126 * avoiding initializing pixels that wont touch the brush */
127 #define PROJ_BUCKET_BRUSH_DIV 4
129 #define PROJ_BUCKET_RECT_MIN 4
130 #define PROJ_BUCKET_RECT_MAX 256
132 #define PROJ_BOUNDBOX_DIV 8
133 #define PROJ_BOUNDBOX_SQUARED (PROJ_BOUNDBOX_DIV * PROJ_BOUNDBOX_DIV)
135 //#define PROJ_DEBUG_PAINT 1
136 //#define PROJ_DEBUG_NOSEAMBLEED 1
137 //#define PROJ_DEBUG_PRINT_CLIP 1
138 #define PROJ_DEBUG_WINCLIP 1
141 #ifndef PROJ_DEBUG_NOSEAMBLEED
142 /* projectFaceSeamFlags options */
143 //#define PROJ_FACE_IGNORE (1<<0) /* When the face is hidden, backfacing or occluded */
144 //#define PROJ_FACE_INIT (1<<1) /* When we have initialized the faces data */
145 #define PROJ_FACE_SEAM1 (1 << 0) /* If this face has a seam on any of its edges */
146 #define PROJ_FACE_SEAM2 (1 << 1)
147 #define PROJ_FACE_SEAM3 (1 << 2)
149 #define PROJ_FACE_NOSEAM1 (1 << 4)
150 #define PROJ_FACE_NOSEAM2 (1 << 5)
151 #define PROJ_FACE_NOSEAM3 (1 << 6)
154 #define PROJ_FACE_WINDING_INIT 1
155 #define PROJ_FACE_WINDING_CW 2
157 /* a slightly scaled down face is used to get fake 3D location for edge pixels in the seams
158 * as this number approaches 1.0f the likelihood increases of float precision errors where
159 * it is occluded by an adjacent face */
160 #define PROJ_FACE_SCALE_SEAM 0.99f
161 #endif /* PROJ_DEBUG_NOSEAMBLEED */
164 #define PROJ_SRC_VIEW 1
165 #define PROJ_SRC_IMAGE_CAM 2
166 #define PROJ_SRC_IMAGE_VIEW 3
167 #define PROJ_SRC_VIEW_FILL 4
169 #define PROJ_VIEW_DATA_ID "view_data"
170 /* viewmat + winmat + clipsta + clipend + is_ortho */
171 #define PROJ_VIEW_DATA_SIZE (4 * 4 + 4 * 4 + 3)
173 #define PROJ_BUCKET_NULL 0
174 #define PROJ_BUCKET_INIT (1 << 0)
175 // #define PROJ_BUCKET_CLONE_INIT (1<<1)
177 /* used for testing doubles, if a point is on a line etc */
178 #define PROJ_GEOM_TOLERANCE 0.00075f
179 #define PROJ_PIXEL_TOLERANCE 0.01f
182 #define PROJ_VERT_CULL 1
184 /* to avoid locking in tile initialization */
185 #define TILE_PENDING POINTER_FROM_INT(-1)
187 /** This is mainly a convenience struct used so we can keep an array of images we use -
188 * their imbufs, etc, in 1 array, When using threads this array is copied for each thread
189 * because 'partRedrawRect' and 'touch' values would not be thread safe */
190 typedef struct ProjPaintImage {
193 ImagePaintPartialRedraw *partRedrawRect;
194 /** Only used to build undo tiles during painting. */
195 volatile void **undoRect;
196 /** The mask accumulation must happen on canvas, not on space screen bucket.
197 * Here we store the mask rectangle. */
198 unsigned short **maskRect;
199 /** Store flag to enforce validation of undo rectangle. */
205 * Handle for stroke (operator customdata)
207 typedef struct ProjStrokeHandle {
208 /* Support for painting from multiple views at once,
209 * currently used to implement symmetry painting,
210 * we can assume at least the first is set while painting. */
211 struct ProjPaintState *ps_views[8];
219 /* trick to bypass regular paint and allow clone picking */
220 bool is_clone_cursor_pick;
222 /* In ProjPaintState, only here for convenience */
227 /* Main projection painting struct passed to all projection painting functions */
228 typedef struct ProjPaintState {
232 Depsgraph *depsgraph;
237 /* the paint color. It can change depending of inverted mode or not */
238 float paint_color[3];
239 float paint_color_linear[3];
243 short tool, blend, mode;
247 /* for symmetry, we need to store modified object matrix */
249 float obmat_imat[4][4];
250 /* end similarities with ImagePaintState */
257 /* projection painting only */
258 /** for multithreading, the first item is sometimes used for non threaded cases too. */
259 MemArena *arena_mt[BLENDER_MAX_THREADS];
260 /** screen sized 2D array, each pixel has a linked list of ProjPixel's */
261 LinkNode **bucketRect;
262 /** bucketRect aligned array linkList of faces overlapping each bucket. */
263 LinkNode **bucketFaces;
264 /** store if the bucks have been initialized. */
265 unsigned char *bucketFlags;
267 /** store options per vert, now only store if the vert is pointing away from the view. */
269 /** The size of the bucket grid, the grid span's screenMin/screenMax
270 * so you can paint outsize the screen or with 2 brushes at once. */
274 /** result of project_paint_pixel_sizeof(), constant per stroke. */
277 /** size of projectImages array. */
280 /** verts projected into floating point screen space. */
281 float (*screenCoords)[4];
282 /** 2D bounds for mesh verts on the screen's plane (screenspace). */
285 /** Calculated from screenMin & screenMax. */
288 /** from the carea or from the projection render. */
291 /* options for projection painting */
293 bool do_layer_stencil;
294 bool do_layer_stencil_inv;
295 bool do_stencil_brush;
296 bool do_material_slots;
298 /** Use raytraced occlusion? - ortherwise will paint right through to the back. */
300 /** ignore faces with normals pointing away,
301 * skips a lot of raycasts if your normals are correctly flipped. */
302 bool do_backfacecull;
303 /** mask out pixels based on their normals. */
305 /** mask out pixels based on cavity. */
307 /** what angle to mask at. */
309 /** cos(normal_angle), faster to compare. */
310 float normal_angle__cos;
311 float normal_angle_inner;
312 float normal_angle_inner__cos;
313 /** difference between normal_angle and normal_angle_inner, for easy access. */
314 float normal_angle_range;
316 /** quick access to (me->editflag & ME_EDIT_PAINT_FACE_SEL) */
319 /** the object is negative scaled. */
321 /** use masking during painting. Some operations such as airbrush may disable. */
323 /** only to avoid running. */
325 /** mask brush is applied before masking. */
327 #ifndef PROJ_DEBUG_NOSEAMBLEED
331 float cloneOffset[2];
333 /** Projection matrix, use for getting screen coords. */
334 float projectMat[4][4];
335 /** inverse of projectMat. */
336 float projectMatInv[4][4];
337 /** View vector, use for do_backfacecull and for ray casting with an ortho viewport. */
339 /** View location in object relative 3D space, so can compare to verts. */
341 float clipsta, clipend;
344 Image *reproject_image;
345 ImBuf *reproject_ibuf;
346 bool reproject_ibuf_free_float;
347 bool reproject_ibuf_free_uchar;
353 /** must lock threads while accessing these. */
354 int context_bucket_x, context_bucket_y;
356 struct CurveMapping *cavity_curve;
357 BlurKernel *blurkernel;
361 /* -------------------------------------------------------------------- */
362 /* Vars shared between multiple views (keep last) */
364 * This data is owned by ``ProjStrokeHandle.ps_views[0]``,
365 * all other views re-use the data.
368 #define PROJ_PAINT_STATE_SHARED_MEMCPY(ps_dst, ps_src) \
369 MEMCPY_STRUCT_OFS(ps_dst, ps_src, is_shared_user)
371 #define PROJ_PAINT_STATE_SHARED_CLEAR(ps) \
372 MEMSET_STRUCT_OFS(ps, 0, is_shared_user)
376 ProjPaintImage *projImages;
377 /** cavity amount for vertices. */
380 #ifndef PROJ_DEBUG_NOSEAMBLEED
381 /** store info about faces, if they are initialized etc*/
383 /** save the winding of the face in uv space,
384 * helps as an extra validation step for seam detection. */
385 char *faceWindingFlags;
386 /** expanded UVs for faces to use as seams. */
387 float (*faceSeamUVs)[3][2];
388 /** Only needed for when seam_bleed_px is enabled, use to find UV seams. */
389 LinkNode **vertFaces;
401 const MVert *mvert_eval;
402 const MEdge *medge_eval;
403 const MPoly *mpoly_eval;
404 const MLoop *mloop_eval;
405 const MLoopTri *mlooptri_eval;
407 const MLoopUV *mloopuv_stencil_eval;
410 * \note These UV layers are aligned to \a mpoly_eval
411 * but each pointer references the start of the layer,
412 * so a loop indirection is needed as well.
414 const MLoopUV **poly_to_loop_uv;
415 /** other UV map, use for cloning between layers. */
416 const MLoopUV **poly_to_loop_uv_clone;
418 /* Actual material for each index, either from object or Mesh datablock... */
419 Material **mat_array;
421 bool use_colormanagement;
424 typedef union pixelPointer {
427 /** 2 ways to access a char buffer. */
428 unsigned int *uint_pt;
429 unsigned char *ch_pt;
432 typedef union pixelStore {
438 typedef struct ProjPixel {
439 /** the floating point screen projection of this pixel. */
445 /** if anyone wants to paint onto more than 65535 images they can bite me. */
446 unsigned short image_index;
447 unsigned char bb_cell_index;
449 /* for various reasons we may want to mask out painting onto this pixel */
452 /* Only used when the airbrush is disabled.
453 * Store the max mask value to avoid painting over an area with a lower opacity
454 * with an advantage that we can avoid touching the pixel at all, if the
455 * new mask value is lower then mask_accum */
456 unsigned short *mask_accum;
458 /* horrible hack, store tile valid flag pointer here to re-validate tiles
459 * used for anchored and drag-dot strokes */
462 PixelPointer origColor;
467 typedef struct ProjPixelClone {
468 struct ProjPixel __pp;
472 /* undo tile pushing */
476 unsigned short tile_width;
478 ProjPaintImage *pjima;
483 /* -------------------------------------------------------------------- */
484 /** \name MLoopTri accessor functions.
487 BLI_INLINE const MPoly *ps_tri_index_to_mpoly(const ProjPaintState *ps, int tri_index)
489 return &ps->mpoly_eval[ps->mlooptri_eval[tri_index].poly];
492 #define PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) \
493 ps->mloop_eval[lt->tri[0]].v, \
494 ps->mloop_eval[lt->tri[1]].v, \
495 ps->mloop_eval[lt->tri[2]].v,
497 #define PS_LOOPTRI_AS_UV_3(uvlayer, lt) \
498 uvlayer[lt->poly][lt->tri[0]].uv, \
499 uvlayer[lt->poly][lt->tri[1]].uv, \
500 uvlayer[lt->poly][lt->tri[2]].uv,
502 #define PS_LOOPTRI_ASSIGN_UV_3(uv_tri, uvlayer, lt) { \
503 (uv_tri)[0] = uvlayer[lt->poly][lt->tri[0]].uv; \
504 (uv_tri)[1] = uvlayer[lt->poly][lt->tri[1]].uv; \
505 (uv_tri)[2] = uvlayer[lt->poly][lt->tri[2]].uv; \
512 /* Finish projection painting structs */
514 static TexPaintSlot *project_paint_face_paint_slot(const ProjPaintState *ps, int tri_index)
516 const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
517 Material *ma = ps->mat_array[mp->mat_nr];
518 return ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
521 static Image *project_paint_face_paint_image(const ProjPaintState *ps, int tri_index)
523 if (ps->do_stencil_brush) {
524 return ps->stencil_ima;
527 const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
528 Material *ma = ps->mat_array[mp->mat_nr];
529 TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_active_slot : NULL;
530 return slot ? slot->ima : ps->canvas_ima;
534 static TexPaintSlot *project_paint_face_clone_slot(const ProjPaintState *ps, int tri_index)
536 const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
537 Material *ma = ps->mat_array[mp->mat_nr];
538 return ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
541 static Image *project_paint_face_clone_image(const ProjPaintState *ps, int tri_index)
543 const MPoly *mp = ps_tri_index_to_mpoly(ps, tri_index);
544 Material *ma = ps->mat_array[mp->mat_nr];
545 TexPaintSlot *slot = ma ? ma->texpaintslot + ma->paint_clone_slot : NULL;
546 return slot ? slot->ima : ps->clone_ima;
549 /* fast projection bucket array lookup, use the safe version for bound checking */
550 static int project_bucket_offset(const ProjPaintState *ps, const float projCoSS[2])
552 /* If we were not dealing with screenspace 2D coords we could simple do...
553 * ps->bucketRect[x + (y*ps->buckets_y)] */
556 * projCoSS[0] - ps->screenMin[0] : zero origin
557 * ... / ps->screen_width : range from 0.0 to 1.0
558 * ... * ps->buckets_x : use as a bucket index
560 * Second multiplication does similar but for vertical offset
562 return ( (int)(((projCoSS[0] - ps->screenMin[0]) / ps->screen_width) * ps->buckets_x)) +
563 (((int)(((projCoSS[1] - ps->screenMin[1]) / ps->screen_height) * ps->buckets_y)) * ps->buckets_x);
566 static int project_bucket_offset_safe(const ProjPaintState *ps, const float projCoSS[2])
568 int bucket_index = project_bucket_offset(ps, projCoSS);
570 if (bucket_index < 0 || bucket_index >= ps->buckets_x * ps->buckets_y) {
578 static float VecZDepthOrtho(
580 const float v1[3], const float v2[3], const float v3[3],
583 barycentric_weights_v2(v1, v2, v3, pt, w);
584 return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]);
587 static float VecZDepthPersp(
589 const float v1[4], const float v2[4], const float v3[4],
592 float wtot_inv, wtot;
595 barycentric_weights_v2_persp(v1, v2, v3, pt, w);
596 /* for the depth we need the weights to match what
597 * barycentric_weights_v2 would return, in this case its easiest just to
598 * undo the 4th axis division and make it unit-sum
600 * don't call barycentric_weights_v2() because our callers expect 'w'
601 * to be weighted from the perspective */
602 w_tmp[0] = w[0] * v1[3];
603 w_tmp[1] = w[1] * v2[3];
604 w_tmp[2] = w[2] * v3[3];
606 wtot = w_tmp[0] + w_tmp[1] + w_tmp[2];
609 wtot_inv = 1.0f / wtot;
611 w_tmp[0] = w_tmp[0] * wtot_inv;
612 w_tmp[1] = w_tmp[1] * wtot_inv;
613 w_tmp[2] = w_tmp[2] * wtot_inv;
615 else /* dummy values for zero area face */
616 w_tmp[0] = w_tmp[1] = w_tmp[2] = 1.0f / 3.0f;
617 /* done mimicking barycentric_weights_v2() */
619 return (v1[2] * w_tmp[0]) + (v2[2] * w_tmp[1]) + (v3[2] * w_tmp[2]);
623 /* Return the top-most face index that the screen space coord 'pt' touches (or -1) */
624 static int project_paint_PickFace(
625 const ProjPaintState *ps, const float pt[2],
631 int best_tri_index = -1;
632 float z_depth_best = FLT_MAX, z_depth;
634 bucket_index = project_bucket_offset_safe(ps, pt);
635 if (bucket_index == -1)
640 /* we could return 0 for 1 face buckets, as long as this function assumes
641 * that the point its testing is only every originated from an existing face */
643 for (node = ps->bucketFaces[bucket_index]; node; node = node->next) {
644 const int tri_index = POINTER_AS_INT(node->link);
645 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
646 const float *vtri_ss[3] = {
647 ps->screenCoords[ps->mloop_eval[lt->tri[0]].v],
648 ps->screenCoords[ps->mloop_eval[lt->tri[1]].v],
649 ps->screenCoords[ps->mloop_eval[lt->tri[2]].v],
653 if (isect_point_tri_v2(pt, UNPACK3(vtri_ss))) {
655 z_depth = VecZDepthOrtho(pt, UNPACK3(vtri_ss), w_tmp);
658 z_depth = VecZDepthPersp(pt, UNPACK3(vtri_ss), w_tmp);
661 if (z_depth < z_depth_best) {
662 best_tri_index = tri_index;
663 z_depth_best = z_depth;
664 copy_v3_v3(w, w_tmp);
669 /** will be -1 or a valid face. */
670 return best_tri_index;
673 /* Converts a uv coord into a pixel location wrapping if the uv is outside 0-1 range */
674 static void uvco_to_wrapped_pxco(const float uv[2], int ibuf_x, int ibuf_y, float *x, float *y)
677 *x = fmodf(uv[0], 1.0f);
678 *y = fmodf(uv[1], 1.0f);
680 if (*x < 0.0f) *x += 1.0f;
681 if (*y < 0.0f) *y += 1.0f;
683 *x = *x * ibuf_x - 0.5f;
684 *y = *y * ibuf_y - 0.5f;
687 /* Set the top-most face color that the screen space coord 'pt' touches
688 * (or return 0 if none touch) */
689 static bool project_paint_PickColor(
690 const ProjPaintState *ps, const float pt[2],
691 float *rgba_fp, unsigned char *rgba, const bool interp)
694 const float *lt_tri_uv[3];
701 tri_index = project_paint_PickFace(ps, pt, w);
706 lt = &ps->mlooptri_eval[tri_index];
707 PS_LOOPTRI_ASSIGN_UV_3(lt_tri_uv, ps->poly_to_loop_uv, lt);
709 interp_v2_v2v2v2(uv, UNPACK3(lt_tri_uv), w);
711 ima = project_paint_face_paint_image(ps, tri_index);
712 /** we must have got the imbuf before getting here. */
713 ibuf = BKE_image_get_first_ibuf(ima);
718 uvco_to_wrapped_pxco(uv, ibuf->x, ibuf->y, &x, &y);
720 if (ibuf->rect_float) {
722 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_fp, x, y);
726 bilinear_interpolation_color_wrap(ibuf, NULL, rgba_tmp_f, x, y);
727 premul_float_to_straight_uchar(rgba, rgba_tmp_f);
732 bilinear_interpolation_color_wrap(ibuf, rgba, NULL, x, y);
735 unsigned char rgba_tmp[4];
736 bilinear_interpolation_color_wrap(ibuf, rgba_tmp, NULL, x, y);
737 straight_uchar_to_premul_float(rgba_fp, rgba_tmp);
742 //xi = (int)((uv[0]*ibuf->x) + 0.5f);
743 //yi = (int)((uv[1]*ibuf->y) + 0.5f);
744 //if (xi < 0 || xi >= ibuf->x || yi < 0 || yi >= ibuf->y) return 0;
747 xi = mod_i((int)(uv[0] * ibuf->x), ibuf->x);
748 yi = mod_i((int)(uv[1] * ibuf->y), ibuf->y);
751 if (ibuf->rect_float) {
752 const float *rgba_tmp_fp = ibuf->rect_float + (xi + yi * ibuf->x * 4);
753 premul_float_to_straight_uchar(rgba, rgba_tmp_fp);
756 *((unsigned int *)rgba) = *(unsigned int *)(((char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4));
761 if (ibuf->rect_float) {
762 copy_v4_v4(rgba_fp, (ibuf->rect_float + ((xi + yi * ibuf->x) * 4)));
765 unsigned char *tmp_ch = ((unsigned char *)ibuf->rect) + ((xi + yi * ibuf->x) * 4);
766 straight_uchar_to_premul_float(rgba_fp, tmp_ch);
770 BKE_image_release_ibuf(ima, ibuf, NULL);
775 * Check if 'pt' is infront of the 3 verts on the Z axis (used for screenspace occlusion test)
777 * - `0`: no occlusion
778 * - `-1`: no occlusion but 2D intersection is true
780 * - `2`: occluded with `w[3]` weights set (need to know in some cases)
782 static int project_paint_occlude_ptv(
784 const float v1[4], const float v2[4], const float v3[4],
785 float w[3], const bool is_ortho)
787 /* if all are behind us, return false */
788 if (v1[2] > pt[2] && v2[2] > pt[2] && v3[2] > pt[2])
791 /* do a 2D point in try intersection */
792 if (!isect_point_tri_v2(pt, v1, v2, v3))
796 /* From here on we know there IS an intersection */
797 /* if ALL of the verts are infront of us then we know it intersects ? */
798 if (v1[2] < pt[2] && v2[2] < pt[2] && v3[2] < pt[2]) {
802 /* we intersect? - find the exact depth at the point of intersection */
803 /* Is this point is occluded by another face? */
805 if (VecZDepthOrtho(pt, v1, v2, v3, w) < pt[2]) return 2;
808 if (VecZDepthPersp(pt, v1, v2, v3, w) < pt[2]) return 2;
815 static int project_paint_occlude_ptv_clip(
817 const float v1[4], const float v2[4], const float v3[4],
818 const float v1_3d[3], const float v2_3d[3], const float v3_3d[3],
819 float w[3], const bool is_ortho, RegionView3D *rv3d)
822 int ret = project_paint_occlude_ptv(pt, v1, v2, v3, w, is_ortho);
827 if (ret == 1) { /* weights not calculated */
829 barycentric_weights_v2(v1, v2, v3, pt, w);
832 barycentric_weights_v2_persp(v1, v2, v3, pt, w);
836 /* Test if we're in the clipped area, */
837 interp_v3_v3v3v3(wco, v1_3d, v2_3d, v3_3d, w);
839 if (!ED_view3d_clipping_test(rv3d, wco, true)) {
847 /* Check if a screenspace location is occluded by any other faces
848 * check, pixelScreenCo must be in screenspace, its Z-Depth only needs to be used for comparison
849 * and doesn't need to be correct in relation to X and Y coords
850 * (this is the case in perspective view) */
851 static bool project_bucket_point_occluded(
852 const ProjPaintState *ps, LinkNode *bucketFace,
853 const int orig_face, const float pixelScreenCo[4])
856 const bool do_clip = ps->rv3d ? (ps->rv3d->rflag & RV3D_CLIPPING) != 0 : 0;
858 /* we could return 0 for 1 face buckets, as long as this function assumes
859 * that the point its testing is only every originated from an existing face */
861 for (; bucketFace; bucketFace = bucketFace->next) {
862 const int tri_index = POINTER_AS_INT(bucketFace->link);
864 if (orig_face != tri_index) {
865 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
866 const float *vtri_ss[3] = {
867 ps->screenCoords[ps->mloop_eval[lt->tri[0]].v],
868 ps->screenCoords[ps->mloop_eval[lt->tri[1]].v],
869 ps->screenCoords[ps->mloop_eval[lt->tri[2]].v],
874 const float *vtri_co[3] = {
875 ps->mvert_eval[ps->mloop_eval[lt->tri[0]].v].co,
876 ps->mvert_eval[ps->mloop_eval[lt->tri[1]].v].co,
877 ps->mvert_eval[ps->mloop_eval[lt->tri[2]].v].co,
879 isect_ret = project_paint_occlude_ptv_clip(
880 pixelScreenCo, UNPACK3(vtri_ss), UNPACK3(vtri_co),
881 w, ps->is_ortho, ps->rv3d);
884 isect_ret = project_paint_occlude_ptv(
885 pixelScreenCo, UNPACK3(vtri_ss),
889 if (isect_ret >= 1) {
890 /* TODO - we may want to cache the first hit,
891 * it is not possible to swap the face order in the list anymore */
899 /* basic line intersection, could move to math_geom.c, 2 points with a horiz line
900 * 1 for an intersection, 2 if the first point is aligned, 3 if the second point is aligned */
902 #define ISECT_TRUE_P1 2
903 #define ISECT_TRUE_P2 3
904 static int line_isect_y(const float p1[2], const float p2[2], const float y_level, float *x_isect)
908 /* are we touching the first point? - no interpolation needed */
909 if (y_level == p1[1]) {
911 return ISECT_TRUE_P1;
913 /* are we touching the second point? - no interpolation needed */
914 if (y_level == p2[1]) {
916 return ISECT_TRUE_P2;
919 /** yuck, horizontal line, we cant do much here. */
920 y_diff = fabsf(p1[1] - p2[1]);
922 if (y_diff < 0.000001f) {
923 *x_isect = (p1[0] + p2[0]) * 0.5f;
927 if (p1[1] > y_level && p2[1] < y_level) {
928 /* (p1[1] - p2[1]); */
929 *x_isect = (p2[0] * (p1[1] - y_level) + p1[0] * (y_level - p2[1])) / y_diff;
932 else if (p1[1] < y_level && p2[1] > y_level) {
933 /* (p2[1] - p1[1]); */
934 *x_isect = (p2[0] * (y_level - p1[1]) + p1[0] * (p2[1] - y_level)) / y_diff;
942 static int line_isect_x(const float p1[2], const float p2[2], const float x_level, float *y_isect)
946 if (x_level == p1[0]) { /* are we touching the first point? - no interpolation needed */
948 return ISECT_TRUE_P1;
950 if (x_level == p2[0]) { /* are we touching the second point? - no interpolation needed */
952 return ISECT_TRUE_P2;
955 /* yuck, horizontal line, we cant do much here */
956 x_diff = fabsf(p1[0] - p2[0]);
958 /* yuck, vertical line, we cant do much here */
959 if (x_diff < 0.000001f) {
960 *y_isect = (p1[0] + p2[0]) * 0.5f;
964 if (p1[0] > x_level && p2[0] < x_level) {
965 /* (p1[0] - p2[0]); */
966 *y_isect = (p2[1] * (p1[0] - x_level) + p1[1] * (x_level - p2[0])) / x_diff;
969 else if (p1[0] < x_level && p2[0] > x_level) {
970 /* (p2[0] - p1[0]); */
971 *y_isect = (p2[1] * (x_level - p1[0]) + p1[1] * (p2[0] - x_level)) / x_diff;
979 /* simple func use for comparing UV locations to check if there are seams.
980 * Its possible this gives incorrect results, when the UVs for 1 face go into the next
981 * tile, but do not do this for the adjacent face, it could return a false positive.
982 * This is so unlikely that Id not worry about it. */
983 #ifndef PROJ_DEBUG_NOSEAMBLEED
984 static bool cmp_uv(const float vec2a[2], const float vec2b[2])
986 /* if the UV's are not between 0.0 and 1.0 */
987 float xa = fmodf(vec2a[0], 1.0f);
988 float ya = fmodf(vec2a[1], 1.0f);
990 float xb = fmodf(vec2b[0], 1.0f);
991 float yb = fmodf(vec2b[1], 1.0f);
993 if (xa < 0.0f) xa += 1.0f;
994 if (ya < 0.0f) ya += 1.0f;
996 if (xb < 0.0f) xb += 1.0f;
997 if (yb < 0.0f) yb += 1.0f;
999 return ((fabsf(xa - xb) < PROJ_GEOM_TOLERANCE) && (fabsf(ya - yb) < PROJ_GEOM_TOLERANCE)) ? 1 : 0;
1003 /* set min_px and max_px to the image space bounds of the UV coords
1004 * return zero if there is no area in the returned rectangle */
1005 #ifndef PROJ_DEBUG_NOSEAMBLEED
1006 static bool pixel_bounds_uv(
1007 const float uv_quad[4][2],
1009 const int ibuf_x, const int ibuf_y
1013 float min_uv[2], max_uv[2];
1015 INIT_MINMAX2(min_uv, max_uv);
1017 minmax_v2v2_v2(min_uv, max_uv, uv_quad[0]);
1018 minmax_v2v2_v2(min_uv, max_uv, uv_quad[1]);
1019 minmax_v2v2_v2(min_uv, max_uv, uv_quad[2]);
1020 minmax_v2v2_v2(min_uv, max_uv, uv_quad[3]);
1022 bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
1023 bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
1025 bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
1026 bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
1028 /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
1030 /* face uses no UV area when quantized to pixels? */
1031 return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
1035 static bool pixel_bounds_array(float (*uv)[2], rcti *bounds_px, const int ibuf_x, const int ibuf_y, int tot)
1038 float min_uv[2], max_uv[2];
1044 INIT_MINMAX2(min_uv, max_uv);
1047 minmax_v2v2_v2(min_uv, max_uv, (*uv));
1051 bounds_px->xmin = (int)(ibuf_x * min_uv[0]);
1052 bounds_px->ymin = (int)(ibuf_y * min_uv[1]);
1054 bounds_px->xmax = (int)(ibuf_x * max_uv[0]) + 1;
1055 bounds_px->ymax = (int)(ibuf_y * max_uv[1]) + 1;
1057 /*printf("%d %d %d %d\n", min_px[0], min_px[1], max_px[0], max_px[1]);*/
1059 /* face uses no UV area when quantized to pixels? */
1060 return (bounds_px->xmin == bounds_px->xmax || bounds_px->ymin == bounds_px->ymax) ? 0 : 1;
1063 #ifndef PROJ_DEBUG_NOSEAMBLEED
1065 static void project_face_winding_init(const ProjPaintState *ps, const int tri_index)
1067 /* detect the winding of faces in uv space */
1068 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1069 const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
1070 float winding = cross_tri_v2(lt_tri_uv[0], lt_tri_uv[1], lt_tri_uv[2]);
1073 ps->faceWindingFlags[tri_index] |= PROJ_FACE_WINDING_CW;
1075 ps->faceWindingFlags[tri_index] |= PROJ_FACE_WINDING_INIT;
1078 /* This function returns 1 if this face has a seam along the 2 face-vert indices
1079 * 'orig_i1_fidx' and 'orig_i2_fidx' */
1080 static bool check_seam(
1081 const ProjPaintState *ps,
1082 const int orig_face, const int orig_i1_fidx, const int orig_i2_fidx,
1083 int *other_face, int *orig_fidx)
1085 const MLoopTri *orig_lt = &ps->mlooptri_eval[orig_face];
1086 const float *orig_lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, orig_lt) };
1087 /* vert indices from face vert order indices */
1088 const unsigned int i1 = ps->mloop_eval[orig_lt->tri[orig_i1_fidx]].v;
1089 const unsigned int i2 = ps->mloop_eval[orig_lt->tri[orig_i2_fidx]].v;
1092 int i1_fidx = -1, i2_fidx = -1;
1094 for (node = ps->vertFaces[i1]; node; node = node->next) {
1095 const int tri_index = POINTER_AS_INT(node->link);
1097 if (tri_index != orig_face) {
1098 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1099 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1100 /* could check if the 2 faces images match here,
1101 * but then there wouldn't be a way to return the opposite face's info */
1104 /* We need to know the order of the verts in the adjacent face
1105 * set the i1_fidx and i2_fidx to (0,1,2,3) */
1106 i1_fidx = BKE_MESH_TESSTRI_VINDEX_ORDER(lt_vtri, i1);
1107 i2_fidx = BKE_MESH_TESSTRI_VINDEX_ORDER(lt_vtri, i2);
1109 /* Only need to check if 'i2_fidx' is valid because we know i1_fidx is the same vert on both faces */
1110 if (i2_fidx != -1) {
1111 const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
1112 Image *tpage = project_paint_face_paint_image(ps, tri_index);
1113 Image *orig_tpage = project_paint_face_paint_image(ps, orig_face);
1115 BLI_assert(i1_fidx != -1);
1117 /* This IS an adjacent face!, now lets check if the UVs are ok */
1119 /* set up the other face */
1120 *other_face = tri_index;
1122 /* we check if difference is 1 here, else we might have a case of edge 2-0 for a tri */
1123 *orig_fidx = (i1_fidx < i2_fidx && (i2_fidx - i1_fidx == 1)) ? i1_fidx : i2_fidx;
1125 /* initialize face winding if needed */
1126 if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_INIT) == 0)
1127 project_face_winding_init(ps, tri_index);
1129 /* first test if they have the same image */
1130 if ((orig_tpage == tpage) &&
1131 cmp_uv(orig_lt_tri_uv[orig_i1_fidx], lt_tri_uv[i1_fidx]) &&
1132 cmp_uv(orig_lt_tri_uv[orig_i2_fidx], lt_tri_uv[i2_fidx]))
1134 /* if faces don't have the same winding in uv space,
1135 * they are on the same side so edge is boundary */
1136 if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_CW) !=
1137 (ps->faceWindingFlags[orig_face] & PROJ_FACE_WINDING_CW))
1142 // printf("SEAM (NONE)\n");
1147 // printf("SEAM (UV GAP)\n");
1153 // printf("SEAM (NO FACE)\n");
1158 #define SMALL_NUMBER 1.e-6f
1159 BLI_INLINE float shell_v2v2_normal_dir_to_dist(float n[2], float d[2])
1161 const float angle_cos = (normalize_v2(n) < SMALL_NUMBER) ? fabsf(dot_v2v2(d, n)) : 0.0f;
1162 return (UNLIKELY(angle_cos < SMALL_NUMBER)) ? 1.0f : (1.0f / angle_cos);
1166 /* Calculate outset UV's, this is not the same as simply scaling the UVs,
1167 * since the outset coords are a margin that keep an even distance from the original UV's,
1168 * note that the image aspect is taken into account */
1169 static void uv_image_outset(
1170 float (*orig_uv)[2], float (*outset_uv)[2], const float scaler,
1171 const int ibuf_x, const int ibuf_y, const bool cw)
1173 /* disallow shell-thickness to outset extreme values,
1174 * otherwise near zero area UV's may extend thousands of pixels. */
1175 const float scale_clamp = 5.0f;
1178 /* pixelspace uv's */
1181 float no1[2], no2[2], no3[2];
1182 float dir1[2], dir2[2], dir3[2];
1185 ibuf_inv[0] = 1.0f / (float)ibuf_x;
1186 ibuf_inv[1] = 1.0f / (float)ibuf_y;
1188 /* make UV's in pixel space so we can */
1189 puv[0][0] = orig_uv[0][0] * ibuf_x;
1190 puv[0][1] = orig_uv[0][1] * ibuf_y;
1192 puv[1][0] = orig_uv[1][0] * ibuf_x;
1193 puv[1][1] = orig_uv[1][1] * ibuf_y;
1195 puv[2][0] = orig_uv[2][0] * ibuf_x;
1196 puv[2][1] = orig_uv[2][1] * ibuf_y;
1198 /* face edge directions */
1199 sub_v2_v2v2(dir1, puv[1], puv[0]);
1200 sub_v2_v2v2(dir2, puv[2], puv[1]);
1201 sub_v2_v2v2(dir3, puv[0], puv[2]);
1206 /* here we just use the orthonormality property (a1, a2) dot (a2, -a1) = 0
1207 * to get normals from the edge directions based on the winding */
1209 no1[0] = -dir3[1] - dir1[1];
1210 no1[1] = dir3[0] + dir1[0];
1211 no2[0] = -dir1[1] - dir2[1];
1212 no2[1] = dir1[0] + dir2[0];
1213 no3[0] = -dir2[1] - dir3[1];
1214 no3[1] = dir2[0] + dir3[0];
1217 no1[0] = dir3[1] + dir1[1];
1218 no1[1] = -dir3[0] - dir1[0];
1219 no2[0] = dir1[1] + dir2[1];
1220 no2[1] = -dir1[0] - dir2[0];
1221 no3[0] = dir2[1] + dir3[1];
1222 no3[1] = -dir2[0] - dir3[0];
1225 a1 = shell_v2v2_normal_dir_to_dist(no1, dir3);
1226 a2 = shell_v2v2_normal_dir_to_dist(no2, dir1);
1227 a3 = shell_v2v2_normal_dir_to_dist(no3, dir2);
1229 CLAMP_MAX(a1, scale_clamp);
1230 CLAMP_MAX(a2, scale_clamp);
1231 CLAMP_MAX(a3, scale_clamp);
1233 mul_v2_fl(no1, a1 * scaler);
1234 mul_v2_fl(no2, a2 * scaler);
1235 mul_v2_fl(no3, a3 * scaler);
1236 add_v2_v2v2(outset_uv[0], puv[0], no1);
1237 add_v2_v2v2(outset_uv[1], puv[1], no2);
1238 add_v2_v2v2(outset_uv[2], puv[2], no3);
1240 mul_v2_v2(outset_uv[0], ibuf_inv);
1241 mul_v2_v2(outset_uv[1], ibuf_inv);
1242 mul_v2_v2(outset_uv[2], ibuf_inv);
1246 * Be tricky with flags, first 4 bits are PROJ_FACE_SEAM1 to 4, last 4 bits are PROJ_FACE_NOSEAM1 to 4
1247 * 1<<i - where i is (0-3)
1249 * If we're multithreadng, make sure threads are locked when this is called
1251 static void project_face_seams_init(const ProjPaintState *ps, const int tri_index)
1253 /* vars for the other face, we also set its flag */
1254 int other_face, other_fidx;
1256 /* next fidx in the face (0,1,2,3) -> (1,2,3,0) or (0,1,2) -> (1,2,0) for a tri */
1259 /* initialize face winding if needed */
1260 if ((ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_INIT) == 0)
1261 project_face_winding_init(ps, tri_index);
1264 if ((ps->faceSeamFlags[tri_index] & (1 << fidx1 | 16 << fidx1)) == 0) {
1265 if (check_seam(ps, tri_index, fidx1, fidx2, &other_face, &other_fidx)) {
1266 ps->faceSeamFlags[tri_index] |= 1 << fidx1;
1267 if (other_face != -1)
1268 ps->faceSeamFlags[other_face] |= 1 << other_fidx;
1271 ps->faceSeamFlags[tri_index] |= 16 << fidx1;
1272 if (other_face != -1) {
1273 /* second 4 bits for disabled */
1274 ps->faceSeamFlags[other_face] |= 16 << other_fidx;
1282 #endif // PROJ_DEBUG_NOSEAMBLEED
1285 /* Converts a UV location to a 3D screenspace location
1286 * Takes a 'uv' and 3 UV coords, and sets the values of pixelScreenCo
1288 * This is used for finding a pixels location in screenspace for painting */
1289 static void screen_px_from_ortho(
1291 const float v1co[3], const float v2co[3], const float v3co[3], /* Screenspace coords */
1292 const float uv1co[2], const float uv2co[2], const float uv3co[2],
1293 float pixelScreenCo[4],
1296 barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1297 interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w);
1300 /* same as screen_px_from_ortho except we
1301 * do perspective correction on the pixel coordinate */
1302 static void screen_px_from_persp(
1304 const float v1co[4], const float v2co[4], const float v3co[4], /* screenspace coords */
1305 const float uv1co[2], const float uv2co[2], const float uv3co[2],
1306 float pixelScreenCo[4],
1310 float wtot_inv, wtot;
1311 barycentric_weights_v2(uv1co, uv2co, uv3co, uv, w);
1313 /* re-weight from the 4th coord of each screen vert */
1314 w_int[0] = w[0] * v1co[3];
1315 w_int[1] = w[1] * v2co[3];
1316 w_int[2] = w[2] * v3co[3];
1318 wtot = w_int[0] + w_int[1] + w_int[2];
1321 wtot_inv = 1.0f / wtot;
1322 w_int[0] *= wtot_inv;
1323 w_int[1] *= wtot_inv;
1324 w_int[2] *= wtot_inv;
1327 w[0] = w[1] = w[2] =
1328 /* dummy values for zero area face */
1329 w_int[0] = w_int[1] = w_int[2] = 1.0f / 3.0f;
1331 /* done re-weighting */
1333 /* do interpolation based on projected weight */
1334 interp_v3_v3v3v3(pixelScreenCo, v1co, v2co, v3co, w_int);
1339 * Set a direction vector based on a screen location.
1340 * (use for perspective view, else we can simply use `ps->viewDir`)
1342 * Similar functionality to #ED_view3d_win_to_vector
1344 * \param r_dir: Resulting direction (length is undefined).
1346 static void screen_px_to_vector_persp(
1347 int winx, int winy, const float projmat_inv[4][4], const float view_pos[3],
1348 const float co_px[2],
1351 r_dir[0] = 2.0f * (co_px[0] / winx) - 1.0f;
1352 r_dir[1] = 2.0f * (co_px[1] / winy) - 1.0f;
1354 mul_project_m4_v3((float(*)[4])projmat_inv, r_dir);
1355 sub_v3_v3(r_dir, view_pos);
1359 * Special function to return the factor to a point along a line in pixel space.
1361 * This is needed since we can't use #line_point_factor_v2 for perspective screen-space coords.
1363 * \param p: 2D screen-space location.
1364 * \param v1, v2: 3D object-space locations.
1366 static float screen_px_line_point_factor_v2_persp(
1367 const ProjPaintState *ps,
1369 const float v1[3], const float v2[3])
1371 const float zero[3] = {0};
1372 float v1_proj[3], v2_proj[3];
1375 screen_px_to_vector_persp(ps->winx, ps->winy, ps->projectMatInv, ps->viewPos, p, dir);
1377 sub_v3_v3v3(v1_proj, v1, ps->viewPos);
1378 sub_v3_v3v3(v2_proj, v2, ps->viewPos);
1380 project_plane_v3_v3v3(v1_proj, v1_proj, dir);
1381 project_plane_v3_v3v3(v2_proj, v2_proj, dir);
1383 return line_point_factor_v2(zero, v1_proj, v2_proj);
1387 static void project_face_pixel(
1388 const float *lt_tri_uv[3], ImBuf *ibuf_other, const float w[3],
1389 unsigned char rgba_ub[4], float rgba_f[4])
1391 float uv_other[2], x, y;
1393 interp_v2_v2v2v2(uv_other, UNPACK3(lt_tri_uv), w);
1396 uvco_to_wrapped_pxco(uv_other, ibuf_other->x, ibuf_other->y, &x, &y);
1398 if (ibuf_other->rect_float) { /* from float to float */
1399 bilinear_interpolation_color_wrap(ibuf_other, NULL, rgba_f, x, y);
1401 else { /* from char to float */
1402 bilinear_interpolation_color_wrap(ibuf_other, rgba_ub, NULL, x, y);
1407 /* run this outside project_paint_uvpixel_init since pixels with mask 0 don't need init */
1408 static float project_paint_uvpixel_mask(
1409 const ProjPaintState *ps,
1410 const int tri_index,
1416 if (ps->do_layer_stencil) {
1417 /* another UV maps image is masking this one's */
1419 Image *other_tpage = ps->stencil_ima;
1421 if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1422 const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index];
1423 const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt_other) };
1425 /* BKE_image_acquire_ibuf - TODO - this may be slow */
1426 unsigned char rgba_ub[4];
1429 project_face_pixel(lt_other_tri_uv, ibuf_other, w, rgba_ub, rgba_f);
1431 if (ibuf_other->rect_float) { /* from float to float */
1432 mask = ((rgba_f[0] + rgba_f[1] + rgba_f[2]) * (1.0f / 3.0f)) * rgba_f[3];
1434 else { /* from char to float */
1435 mask = ((rgba_ub[0] + rgba_ub[1] + rgba_ub[2]) * (1.0f / (255.0f * 3.0f))) * (rgba_ub[3] * (1.0f / 255.0f));
1438 BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1440 if (!ps->do_layer_stencil_inv) {
1441 /* matching the gimps layer mask black/white rules, white==full opacity */
1442 mask = (1.0f - mask);
1457 if (ps->do_mask_cavity) {
1458 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1459 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1460 float ca1, ca2, ca3, ca_mask;
1461 ca1 = ps->cavities[lt_vtri[0]];
1462 ca2 = ps->cavities[lt_vtri[1]];
1463 ca3 = ps->cavities[lt_vtri[2]];
1465 ca_mask = w[0] * ca1 + w[1] * ca2 + w[2] * ca3;
1466 ca_mask = curvemapping_evaluateF(ps->cavity_curve, 0, ca_mask);
1467 CLAMP(ca_mask, 0.0f, 1.0f);
1471 /* calculate mask */
1472 if (ps->do_mask_normal) {
1473 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
1474 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
1475 const MPoly *mp = &ps->mpoly_eval[lt->poly];
1476 float no[3], angle_cos;
1478 if (mp->flag & ME_SMOOTH) {
1479 const short *no1, *no2, *no3;
1480 no1 = ps->mvert_eval[lt_vtri[0]].no;
1481 no2 = ps->mvert_eval[lt_vtri[1]].no;
1482 no3 = ps->mvert_eval[lt_vtri[2]].no;
1484 no[0] = w[0] * no1[0] + w[1] * no2[0] + w[2] * no3[0];
1485 no[1] = w[0] * no1[1] + w[1] * no2[1] + w[2] * no3[1];
1486 no[2] = w[0] * no1[2] + w[1] * no2[2] + w[2] * no3[2];
1492 /* normalizing per pixel isn't optimal, we could cache or check ps->*/
1494 ps->mvert_eval[lt_vtri[0]].co,
1495 ps->mvert_eval[lt_vtri[1]].co,
1496 ps->mvert_eval[lt_vtri[2]].co);
1498 /* don't use because some modifiers dont have normal data (subsurf for eg) */
1499 copy_v3_v3(no, (float *)ps->dm->getTessFaceData(ps->dm, tri_index, CD_NORMAL));
1503 if (UNLIKELY(ps->is_flip_object)) {
1507 /* now we can use the normal as a mask */
1509 angle_cos = dot_v3v3(ps->viewDir, no);
1512 /* Annoying but for the perspective view we need to get the pixels location in 3D space :/ */
1513 float viewDirPersp[3];
1514 const float *co1, *co2, *co3;
1515 co1 = ps->mvert_eval[lt_vtri[0]].co;
1516 co2 = ps->mvert_eval[lt_vtri[1]].co;
1517 co3 = ps->mvert_eval[lt_vtri[2]].co;
1519 /* Get the direction from the viewPoint to the pixel and normalize */
1520 viewDirPersp[0] = (ps->viewPos[0] - (w[0] * co1[0] + w[1] * co2[0] + w[2] * co3[0]));
1521 viewDirPersp[1] = (ps->viewPos[1] - (w[0] * co1[1] + w[1] * co2[1] + w[2] * co3[1]));
1522 viewDirPersp[2] = (ps->viewPos[2] - (w[0] * co1[2] + w[1] * co2[2] + w[2] * co3[2]));
1523 normalize_v3(viewDirPersp);
1524 if (UNLIKELY(ps->is_flip_object)) {
1525 negate_v3(viewDirPersp);
1528 angle_cos = dot_v3v3(viewDirPersp, no);
1531 /* If backface culling is disabled, allow painting on back faces. */
1532 if (!ps->do_backfacecull) {
1533 angle_cos = fabsf(angle_cos);
1536 if (angle_cos <= ps->normal_angle__cos) {
1537 /* outsize the normal limit*/
1540 else if (angle_cos < ps->normal_angle_inner__cos) {
1541 mask *= (ps->normal_angle - acosf(angle_cos)) / ps->normal_angle_range;
1542 } /* otherwise no mask normal is needed, were within the limit */
1545 /* This only works when the opacity dosnt change while painting, stylus pressure messes with this
1546 * so don't use it. */
1547 // if (ps->is_airbrush == 0) mask *= BKE_brush_alpha_get(ps->brush);
1552 static int project_paint_pixel_sizeof(const short tool)
1554 if ((tool == PAINT_TOOL_CLONE) || (tool == PAINT_TOOL_SMEAR)) {
1555 return sizeof(ProjPixelClone);
1558 return sizeof(ProjPixel);
1562 static int project_paint_undo_subtiles(const TileInfo *tinf, int tx, int ty)
1564 ProjPaintImage *pjIma = tinf->pjima;
1565 int tile_index = tx + ty * tinf->tile_width;
1566 bool generate_tile = false;
1568 /* double check lock to avoid locking */
1569 if (UNLIKELY(!pjIma->undoRect[tile_index])) {
1571 BLI_spin_lock(tinf->lock);
1572 if (LIKELY(!pjIma->undoRect[tile_index])) {
1573 pjIma->undoRect[tile_index] = TILE_PENDING;
1574 generate_tile = true;
1577 BLI_spin_unlock(tinf->lock);
1581 if (generate_tile) {
1582 ListBase *undo_tiles = ED_image_undo_get_tiles();
1583 volatile void *undorect;
1585 undorect = image_undo_push_tile(
1586 undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
1587 tx, ty, &pjIma->maskRect[tile_index], &pjIma->valid[tile_index], true, false);
1590 undorect = image_undo_push_tile(
1591 undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
1592 tx, ty, NULL, &pjIma->valid[tile_index], true, false);
1595 pjIma->ibuf->userflags |= IB_BITMAPDIRTY;
1596 /* tile ready, publish */
1598 BLI_spin_lock(tinf->lock);
1599 pjIma->undoRect[tile_index] = undorect;
1601 BLI_spin_unlock(tinf->lock);
1608 /* run this function when we know a bucket's, face's pixel can be initialized,
1609 * return the ProjPixel which is added to 'ps->bucketRect[bucket_index]' */
1610 static ProjPixel *project_paint_uvpixel_init(
1611 const ProjPaintState *ps,
1613 const TileInfo *tinf,
1616 const int tri_index,
1617 const float pixelScreenCo[4],
1618 const float world_spaceCo[3],
1621 ProjPixel *projPixel;
1623 int x_round, y_round;
1625 /* volatile is important here to ensure pending check is not optimized away by compiler*/
1626 volatile int tile_index;
1628 ProjPaintImage *projima = tinf->pjima;
1629 ImBuf *ibuf = projima->ibuf;
1630 /* wrap pixel location */
1632 x_px = mod_i(x_px, ibuf->x);
1633 y_px = mod_i(y_px, ibuf->y);
1635 BLI_assert(ps->pixel_sizeof == project_paint_pixel_sizeof(ps->tool));
1636 projPixel = BLI_memarena_alloc(arena, ps->pixel_sizeof);
1638 /* calculate the undo tile offset of the pixel, used to store the original
1639 * pixel color and accumulated mask if any */
1640 x_tile = x_px >> IMAPAINT_TILE_BITS;
1641 y_tile = y_px >> IMAPAINT_TILE_BITS;
1643 x_round = x_tile * IMAPAINT_TILE_SIZE;
1644 y_round = y_tile * IMAPAINT_TILE_SIZE;
1645 //memset(projPixel, 0, size);
1647 tile_offset = (x_px - x_round) + (y_px - y_round) * IMAPAINT_TILE_SIZE;
1648 tile_index = project_paint_undo_subtiles(tinf, x_tile, y_tile);
1650 /* other thread may be initializing the tile so wait here */
1651 while (projima->undoRect[tile_index] == TILE_PENDING)
1654 BLI_assert(tile_index < (IMAPAINT_TILE_NUMBER(ibuf->x) * IMAPAINT_TILE_NUMBER(ibuf->y)));
1655 BLI_assert(tile_offset < (IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE));
1657 projPixel->valid = projima->valid[tile_index];
1659 if (ibuf->rect_float) {
1660 projPixel->pixel.f_pt = ibuf->rect_float + ((x_px + y_px * ibuf->x) * 4);
1661 projPixel->origColor.f_pt = (float *)projima->undoRect[tile_index] + 4 * tile_offset;
1662 zero_v4(projPixel->newColor.f);
1665 projPixel->pixel.ch_pt = (unsigned char *)(ibuf->rect + (x_px + y_px * ibuf->x));
1666 projPixel->origColor.uint_pt = (unsigned int *)projima->undoRect[tile_index] + tile_offset;
1667 projPixel->newColor.uint = 0;
1670 /* screenspace unclamped, we could keep its z and w values but don't need them at the moment */
1671 if (ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
1672 copy_v3_v3(projPixel->worldCoSS, world_spaceCo);
1675 copy_v2_v2(projPixel->projCoSS, pixelScreenCo);
1677 projPixel->x_px = x_px;
1678 projPixel->y_px = y_px;
1680 projPixel->mask = (unsigned short)(mask * 65535);
1682 projPixel->mask_accum = projima->maskRect[tile_index] + tile_offset;
1684 projPixel->mask_accum = NULL;
1686 /* which bounding box cell are we in?, needed for undo */
1687 projPixel->bb_cell_index = ((int)(((float)x_px / (float)ibuf->x) * PROJ_BOUNDBOX_DIV)) +
1688 ((int)(((float)y_px / (float)ibuf->y) * PROJ_BOUNDBOX_DIV)) * PROJ_BOUNDBOX_DIV;
1690 /* done with view3d_project_float inline */
1691 if (ps->tool == PAINT_TOOL_CLONE) {
1692 if (ps->poly_to_loop_uv_clone) {
1694 Image *other_tpage = project_paint_face_clone_image(ps, tri_index);
1696 if (other_tpage && (ibuf_other = BKE_image_acquire_ibuf(other_tpage, NULL, NULL))) {
1697 const MLoopTri *lt_other = &ps->mlooptri_eval[tri_index];
1698 const float *lt_other_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv_clone, lt_other) };
1700 /* BKE_image_acquire_ibuf - TODO - this may be slow */
1702 if (ibuf->rect_float) {
1703 if (ibuf_other->rect_float) { /* from float to float */
1704 project_face_pixel(lt_other_tri_uv, ibuf_other, w, NULL, ((ProjPixelClone *)projPixel)->clonepx.f);
1706 else { /* from char to float */
1707 unsigned char rgba_ub[4];
1709 project_face_pixel(lt_other_tri_uv, ibuf_other, w, rgba_ub, NULL);
1710 if (ps->use_colormanagement) {
1711 srgb_to_linearrgb_uchar4(rgba, rgba_ub);
1714 rgba_uchar_to_float(rgba, rgba_ub);
1716 straight_to_premul_v4_v4(((ProjPixelClone *)projPixel)->clonepx.f, rgba);
1720 if (ibuf_other->rect_float) { /* float to char */
1722 project_face_pixel(lt_other_tri_uv, ibuf_other, w, NULL, rgba);
1723 premul_to_straight_v4(rgba);
1724 if (ps->use_colormanagement) {
1725 linearrgb_to_srgb_uchar3(((ProjPixelClone *)projPixel)->clonepx.ch, rgba);
1728 rgb_float_to_uchar(((ProjPixelClone *)projPixel)->clonepx.ch, rgba);
1730 ((ProjPixelClone *)projPixel)->clonepx.ch[3] = rgba[3] * 255;
1732 else { /* char to char */
1733 project_face_pixel(lt_other_tri_uv, ibuf_other, w, ((ProjPixelClone *)projPixel)->clonepx.ch, NULL);
1737 BKE_image_release_ibuf(other_tpage, ibuf_other, NULL);
1740 if (ibuf->rect_float) {
1741 ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0;
1744 ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0;
1751 sub_v2_v2v2(co, projPixel->projCoSS, ps->cloneOffset);
1753 /* no need to initialize the bucket, we're only checking buckets faces and for this
1754 * the faces are already initialized in project_paint_delayed_face_init(...) */
1755 if (ibuf->rect_float) {
1756 if (!project_paint_PickColor(ps, co, ((ProjPixelClone *)projPixel)->clonepx.f, NULL, 1)) {
1757 /* zero alpha - ignore */
1758 ((ProjPixelClone *)projPixel)->clonepx.f[3] = 0;
1762 if (!project_paint_PickColor(ps, co, NULL, ((ProjPixelClone *)projPixel)->clonepx.ch, 1)) {
1763 /* zero alpha - ignore */
1764 ((ProjPixelClone *)projPixel)->clonepx.ch[3] = 0;
1770 #ifdef PROJ_DEBUG_PAINT
1771 if (ibuf->rect_float) projPixel->pixel.f_pt[0] = 0;
1772 else projPixel->pixel.ch_pt[0] = 0;
1774 /* pointer arithmetic */
1775 projPixel->image_index = projima - ps->projImages;
1780 static bool line_clip_rect2f(
1781 const rctf *cliprect,
1783 const float l1[2], const float l2[2],
1784 float l1_clip[2], float l2_clip[2])
1786 /* first account for horizontal, then vertical lines */
1788 if (fabsf(l1[1] - l2[1]) < PROJ_PIXEL_TOLERANCE) {
1789 /* is the line out of range on its Y axis? */
1790 if (l1[1] < rect->ymin || l1[1] > rect->ymax) {
1793 /* line is out of range on its X axis */
1794 if ((l1[0] < rect->xmin && l2[0] < rect->xmin) || (l1[0] > rect->xmax && l2[0] > rect->xmax)) {
1799 /* this is a single point (or close to)*/
1800 if (fabsf(l1[0] - l2[0]) < PROJ_PIXEL_TOLERANCE) {
1801 if (BLI_rctf_isect_pt_v(rect, l1)) {
1802 copy_v2_v2(l1_clip, l1);
1803 copy_v2_v2(l2_clip, l2);
1811 copy_v2_v2(l1_clip, l1);
1812 copy_v2_v2(l2_clip, l2);
1813 CLAMP(l1_clip[0], rect->xmin, rect->xmax);
1814 CLAMP(l2_clip[0], rect->xmin, rect->xmax);
1817 else if (fabsf(l1[0] - l2[0]) < PROJ_PIXEL_TOLERANCE) {
1818 /* is the line out of range on its X axis? */
1819 if (l1[0] < rect->xmin || l1[0] > rect->xmax) {
1823 /* line is out of range on its Y axis */
1824 if ((l1[1] < rect->ymin && l2[1] < rect->ymin) || (l1[1] > rect->ymax && l2[1] > rect->ymax)) {
1828 /* this is a single point (or close to)*/
1829 if (fabsf(l1[1] - l2[1]) < PROJ_PIXEL_TOLERANCE) {
1830 if (BLI_rctf_isect_pt_v(rect, l1)) {
1831 copy_v2_v2(l1_clip, l1);
1832 copy_v2_v2(l2_clip, l2);
1840 copy_v2_v2(l1_clip, l1);
1841 copy_v2_v2(l2_clip, l2);
1842 CLAMP(l1_clip[1], rect->ymin, rect->ymax);
1843 CLAMP(l2_clip[1], rect->ymin, rect->ymax);
1851 /* Done with vertical lines */
1853 /* are either of the points inside the rectangle ? */
1854 if (BLI_rctf_isect_pt_v(rect, l1)) {
1855 copy_v2_v2(l1_clip, l1);
1859 if (BLI_rctf_isect_pt_v(rect, l2)) {
1860 copy_v2_v2(l2_clip, l2);
1864 /* line inside rect */
1865 if (ok1 && ok2) return 1;
1868 if (line_isect_y(l1, l2, rect->ymin, &isect) && (isect >= cliprect->xmin) && (isect <= cliprect->xmax)) {
1869 if (l1[1] < l2[1]) { /* line 1 is outside */
1871 l1_clip[1] = rect->ymin;
1876 l2_clip[1] = rect->ymin;
1881 if (ok1 && ok2) return 1;
1883 if (line_isect_y(l1, l2, rect->ymax, &isect) && (isect >= cliprect->xmin) && (isect <= cliprect->xmax)) {
1884 if (l1[1] > l2[1]) { /* line 1 is outside */
1886 l1_clip[1] = rect->ymax;
1891 l2_clip[1] = rect->ymax;
1896 if (ok1 && ok2) return 1;
1899 if (line_isect_x(l1, l2, rect->xmin, &isect) && (isect >= cliprect->ymin) && (isect <= cliprect->ymax)) {
1900 if (l1[0] < l2[0]) { /* line 1 is outside */
1901 l1_clip[0] = rect->xmin;
1906 l2_clip[0] = rect->xmin;
1912 if (ok1 && ok2) return 1;
1914 if (line_isect_x(l1, l2, rect->xmax, &isect) && (isect >= cliprect->ymin) && (isect <= cliprect->ymax)) {
1915 if (l1[0] > l2[0]) { /* line 1 is outside */
1916 l1_clip[0] = rect->xmax;
1921 l2_clip[0] = rect->xmax;
1939 * Scale the tri about its center
1940 * scaling by #PROJ_FACE_SCALE_SEAM (0.99x) is used for getting fake UV pixel coords that are on the
1941 * edge of the face but slightly inside it occlusion tests don't return hits on adjacent faces
1943 #ifndef PROJ_DEBUG_NOSEAMBLEED
1945 static void scale_tri(float insetCos[3][3], const float *origCos[4], const float inset)
1948 cent[0] = (origCos[0][0] + origCos[1][0] + origCos[2][0]) * (1.0f / 3.0f);
1949 cent[1] = (origCos[0][1] + origCos[1][1] + origCos[2][1]) * (1.0f / 3.0f);
1950 cent[2] = (origCos[0][2] + origCos[1][2] + origCos[2][2]) * (1.0f / 3.0f);
1952 sub_v3_v3v3(insetCos[0], origCos[0], cent);
1953 sub_v3_v3v3(insetCos[1], origCos[1], cent);
1954 sub_v3_v3v3(insetCos[2], origCos[2], cent);
1956 mul_v3_fl(insetCos[0], inset);
1957 mul_v3_fl(insetCos[1], inset);
1958 mul_v3_fl(insetCos[2], inset);
1960 add_v3_v3(insetCos[0], cent);
1961 add_v3_v3(insetCos[1], cent);
1962 add_v3_v3(insetCos[2], cent);
1964 #endif //PROJ_DEBUG_NOSEAMBLEED
1966 static float len_squared_v2v2_alt(const float v1[2], const float v2_1, const float v2_2)
1972 return x * x + y * y;
1975 /* note, use a squared value so we can use len_squared_v2v2
1976 * be sure that you have done a bounds check first or this may fail */
1977 /* only give bucket_bounds as an arg because we need it elsewhere */
1978 static bool project_bucket_isect_circle(const float cent[2], const float radius_squared, const rctf *bucket_bounds)
1981 /* Would normally to a simple intersection test, however we know the bounds of these 2 already intersect
1982 * so we only need to test if the center is inside the vertical or horizontal bounds on either axis,
1983 * this is even less work then an intersection test
1986 if (BLI_rctf_isect_pt_v(bucket_bounds, cent))
1990 if ((bucket_bounds->xmin <= cent[0] && bucket_bounds->xmax >= cent[0]) ||
1991 (bucket_bounds->ymin <= cent[1] && bucket_bounds->ymax >= cent[1]))
1996 /* out of bounds left */
1997 if (cent[0] < bucket_bounds->xmin) {
1998 /* lower left out of radius test */
1999 if (cent[1] < bucket_bounds->ymin) {
2000 return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
2003 else if (cent[1] > bucket_bounds->ymax) {
2004 return (len_squared_v2v2_alt(cent, bucket_bounds->xmin, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
2007 else if (cent[0] > bucket_bounds->xmax) {
2008 /* lower right out of radius test */
2009 if (cent[1] < bucket_bounds->ymin) {
2010 return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymin) < radius_squared) ? 1 : 0;
2012 /* top right test */
2013 else if (cent[1] > bucket_bounds->ymax) {
2014 return (len_squared_v2v2_alt(cent, bucket_bounds->xmax, bucket_bounds->ymax) < radius_squared) ? 1 : 0;
2023 /* Note for rect_to_uvspace_ortho() and rect_to_uvspace_persp()
2024 * in ortho view this function gives good results when bucket_bounds are outside the triangle
2025 * however in some cases, perspective view will mess up with faces that have minimal screenspace area
2026 * (viewed from the side)
2028 * for this reason its not reliable in this case so we'll use the Simple Barycentric'
2029 * funcs that only account for points inside the triangle.
2030 * however switching back to this for ortho is always an option */
2032 static void rect_to_uvspace_ortho(
2033 const rctf *bucket_bounds,
2034 const float *v1coSS, const float *v2coSS, const float *v3coSS,
2035 const float *uv1co, const float *uv2co, const float *uv3co,
2036 float bucket_bounds_uv[4][2],
2042 /* get the UV space bounding box */
2043 uv[0] = bucket_bounds->xmax;
2044 uv[1] = bucket_bounds->ymin;
2045 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2046 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
2048 //uv[0] = bucket_bounds->xmax; // set above
2049 uv[1] = bucket_bounds->ymax;
2050 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2051 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
2053 uv[0] = bucket_bounds->xmin;
2054 //uv[1] = bucket_bounds->ymax; // set above
2055 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2056 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
2058 //uv[0] = bucket_bounds->xmin; // set above
2059 uv[1] = bucket_bounds->ymin;
2060 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, uv, w);
2061 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
2064 /* same as above but use barycentric_weights_v2_persp */
2065 static void rect_to_uvspace_persp(
2066 const rctf *bucket_bounds,
2067 const float *v1coSS, const float *v2coSS, const float *v3coSS,
2068 const float *uv1co, const float *uv2co, const float *uv3co,
2069 float bucket_bounds_uv[4][2],
2076 /* get the UV space bounding box */
2077 uv[0] = bucket_bounds->xmax;
2078 uv[1] = bucket_bounds->ymin;
2079 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2080 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 3 : 0], uv1co, uv2co, uv3co, w);
2082 //uv[0] = bucket_bounds->xmax; // set above
2083 uv[1] = bucket_bounds->ymax;
2084 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2085 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 2 : 1], uv1co, uv2co, uv3co, w);
2087 uv[0] = bucket_bounds->xmin;
2088 //uv[1] = bucket_bounds->ymax; // set above
2089 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2090 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 1 : 2], uv1co, uv2co, uv3co, w);
2092 //uv[0] = bucket_bounds->xmin; // set above
2093 uv[1] = bucket_bounds->ymin;
2094 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, uv, w);
2095 interp_v2_v2v2v2(bucket_bounds_uv[flip ? 0 : 3], uv1co, uv2co, uv3co, w);
2098 /* This works as we need it to but we can save a few steps and not use it */
2101 static float angle_2d_clockwise(const float p1[2], const float p2[2], const float p3[2])
2105 v1[0] = p1[0] - p2[0]; v1[1] = p1[1] - p2[1];
2106 v2[0] = p3[0] - p2[0]; v2[1] = p3[1] - p2[1];
2108 return -atan2f(v1[0] * v2[1] - v1[1] * v2[0], v1[0] * v2[0] + v1[1] * v2[1]);
2113 #define ISECT_2 (1 << 1)
2114 #define ISECT_3 (1 << 2)
2115 #define ISECT_4 (1 << 3)
2116 #define ISECT_ALL3 ((1 << 3) - 1)
2117 #define ISECT_ALL4 ((1 << 4) - 1)
2119 /* limit must be a fraction over 1.0f */
2120 static bool IsectPT2Df_limit(
2122 const float v1[2], const float v2[2], const float v3[2],
2125 return ((area_tri_v2(pt, v1, v2) +
2126 area_tri_v2(pt, v2, v3) +
2127 area_tri_v2(pt, v3, v1)) / (area_tri_v2(v1, v2, v3))) < limit;
2130 /* Clip the face by a bucket and set the uv-space bucket_bounds_uv
2131 * so we have the clipped UV's to do pixel intersection tests with
2133 static int float_z_sort_flip(const void *p1, const void *p2)
2135 return (((float *)p1)[2] < ((float *)p2)[2] ? 1 : -1);
2138 static int float_z_sort(const void *p1, const void *p2)
2140 return (((float *)p1)[2] < ((float *)p2)[2] ? -1 : 1);
2143 /* assumes one point is within the rectangle */
2144 static bool line_rect_clip(
2146 const float l1[4], const float l2[4],
2147 const float uv1[2], const float uv2[2],
2148 float uv[2], bool is_ortho)
2150 float min = FLT_MAX, tmp;
2151 float xlen = l2[0] - l1[0];
2152 float ylen = l2[1] - l1[1];
2154 /* 0.1 might seem too much, but remember, this is pixels! */
2156 if ((l1[0] - rect->xmin) * (l2[0] - rect->xmin) <= 0) {
2158 min = min_ff((tmp - l1[0]) / xlen, min);
2160 else if ((l1[0] - rect->xmax) * (l2[0] - rect->xmax) < 0) {
2162 min = min_ff((tmp - l1[0]) / xlen, min);
2167 if ((l1[1] - rect->ymin) * (l2[1] - rect->ymin) <= 0) {
2169 min = min_ff((tmp - l1[1]) / ylen, min);
2171 else if ((l1[1] - rect->ymax) * (l2[1] - rect->ymax) < 0) {
2173 min = min_ff((tmp - l1[1]) / ylen, min);
2180 tmp = (is_ortho) ? 1.0f : (l1[3] + min * (l2[3] - l1[3]));
2182 uv[0] = (uv1[0] + min / tmp * (uv2[0] - uv1[0]));
2183 uv[1] = (uv1[1] + min / tmp * (uv2[1] - uv1[1]));
2189 static void project_bucket_clip_face(
2190 const bool is_ortho, const bool is_flip_object,
2191 const rctf *cliprect,
2192 const rctf *bucket_bounds,
2193 const float *v1coSS, const float *v2coSS, const float *v3coSS,
2194 const float *uv1co, const float *uv2co, const float *uv3co,
2195 float bucket_bounds_uv[8][2],
2196 int *tot, bool cull)
2198 int inside_bucket_flag = 0;
2199 int inside_face_flag = 0;
2201 bool collinear = false;
2203 float bucket_bounds_ss[4][2];
2205 /* detect pathological case where face the three vertices are almost collinear in screen space.
2206 * mostly those will be culled but when flood filling or with
2207 * smooth shading it's a possibility */
2208 if (min_fff(dist_squared_to_line_v2(v1coSS, v2coSS, v3coSS),
2209 dist_squared_to_line_v2(v2coSS, v3coSS, v1coSS),
2210 dist_squared_to_line_v2(v3coSS, v1coSS, v2coSS)) < PROJ_PIXEL_TOLERANCE)
2215 /* get the UV space bounding box */
2216 inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v1coSS);
2217 inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v2coSS) << 1;
2218 inside_bucket_flag |= BLI_rctf_isect_pt_v(bucket_bounds, v3coSS) << 2;
2220 if (inside_bucket_flag == ISECT_ALL3) {
2221 /* is_flip_object is used here because we use the face winding */
2222 flip = (((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) != is_flip_object) !=
2223 (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2225 /* all screenspace points are inside the bucket bounding box,
2226 * this means we don't need to clip and can simply return the UVs */
2227 if (flip) { /* facing the back? */
2228 copy_v2_v2(bucket_bounds_uv[0], uv3co);
2229 copy_v2_v2(bucket_bounds_uv[1], uv2co);
2230 copy_v2_v2(bucket_bounds_uv[2], uv1co);
2233 copy_v2_v2(bucket_bounds_uv[0], uv1co);
2234 copy_v2_v2(bucket_bounds_uv[1], uv2co);
2235 copy_v2_v2(bucket_bounds_uv[2], uv3co);
2241 /* handle pathological case here,
2242 * no need for further intersections below since tringle area is almost zero */
2251 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++; }
2253 flag = inside_bucket_flag & (ISECT_1 | ISECT_2);
2254 if (flag && flag != (ISECT_1 | ISECT_2)) {
2255 if (line_rect_clip(bucket_bounds, v1coSS, v2coSS, uv1co, uv2co, bucket_bounds_uv[*tot], is_ortho))
2259 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++; }
2261 flag = inside_bucket_flag & (ISECT_2 | ISECT_3);
2262 if (flag && flag != (ISECT_2 | ISECT_3)) {
2263 if (line_rect_clip(bucket_bounds, v2coSS, v3coSS, uv2co, uv3co, bucket_bounds_uv[*tot], is_ortho))
2267 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++; }
2269 flag = inside_bucket_flag & (ISECT_3 | ISECT_1);
2270 if (flag && flag != (ISECT_3 | ISECT_1)) {
2271 if (line_rect_clip(bucket_bounds, v3coSS, v1coSS, uv3co, uv1co, bucket_bounds_uv[*tot], is_ortho))
2276 /* no intersections to speak of, but more probable is that all face is just outside the
2277 * rectangle and culled due to float precision issues. Since above tests have failed,
2278 * just dump triangle as is for painting */
2280 copy_v2_v2(bucket_bounds_uv[*tot], uv1co); (*tot)++;
2281 copy_v2_v2(bucket_bounds_uv[*tot], uv2co); (*tot)++;
2282 copy_v2_v2(bucket_bounds_uv[*tot], uv3co); (*tot)++;
2289 /* get the UV space bounding box */
2290 /* use IsectPT2Df_limit here so we catch points are are touching the tri edge
2291 * (or a small fraction over) */
2292 bucket_bounds_ss[0][0] = bucket_bounds->xmax;
2293 bucket_bounds_ss[0][1] = bucket_bounds->ymin;
2294 inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[0], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_1 : 0);
2296 bucket_bounds_ss[1][0] = bucket_bounds->xmax;
2297 bucket_bounds_ss[1][1] = bucket_bounds->ymax;
2298 inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[1], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_2 : 0);
2300 bucket_bounds_ss[2][0] = bucket_bounds->xmin;
2301 bucket_bounds_ss[2][1] = bucket_bounds->ymax;
2302 inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[2], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_3 : 0);
2304 bucket_bounds_ss[3][0] = bucket_bounds->xmin;
2305 bucket_bounds_ss[3][1] = bucket_bounds->ymin;
2306 inside_face_flag |= (IsectPT2Df_limit(bucket_bounds_ss[3], v1coSS, v2coSS, v3coSS, 1 + PROJ_GEOM_TOLERANCE) ? ISECT_4 : 0);
2308 flip = ((line_point_side_v2(v1coSS, v2coSS, v3coSS) > 0.0f) !=
2309 (line_point_side_v2(uv1co, uv2co, uv3co) > 0.0f));
2311 if (inside_face_flag == ISECT_ALL4) {
2312 /* bucket is totally inside the screenspace face, we can safely use weights */
2315 rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2318 rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, bucket_bounds_uv, flip);
2325 /* The Complicated Case!
2327 * The 2 cases above are where the face is inside the bucket
2328 * or the bucket is inside the face.
2330 * we need to make a convex polyline from the intersection between the screenspace face
2331 * and the bucket bounds.
2333 * There are a number of ways this could be done, currently it just collects all
2334 * intersecting verts, and line intersections, then sorts them clockwise, this is
2335 * a lot easier then evaluating the geometry to do a correct clipping on both shapes.
2339 /* Add a bunch of points, we know must make up the convex hull
2340 * which is the clipped rect and triangle */
2342 /* Maximum possible 6 intersections when using a rectangle and triangle */
2344 /* The 3rd float is used to store angle for qsort(), NOT as a Z location */
2345 float isectVCosSS[8][3];
2346 float v1_clipSS[2], v2_clipSS[2];
2350 float cent[2] = {0.0f, 0.0f};
2351 /*float up[2] = {0.0f, 1.0f};*/
2357 if (inside_face_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[0]); (*tot)++; }
2358 if (inside_face_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[1]); (*tot)++; }
2359 if (inside_face_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[2]); (*tot)++; }
2360 if (inside_face_flag & ISECT_4) { copy_v2_v2(isectVCosSS[*tot], bucket_bounds_ss[3]); (*tot)++; }
2362 if (inside_bucket_flag & ISECT_1) { copy_v2_v2(isectVCosSS[*tot], v1coSS); (*tot)++; }
2363 if (inside_bucket_flag & ISECT_2) { copy_v2_v2(isectVCosSS[*tot], v2coSS); (*tot)++; }
2364 if (inside_bucket_flag & ISECT_3) { copy_v2_v2(isectVCosSS[*tot], v3coSS); (*tot)++; }
2366 if ((inside_bucket_flag & (ISECT_1 | ISECT_2)) != (ISECT_1 | ISECT_2)) {
2367 if (line_clip_rect2f(cliprect, bucket_bounds, v1coSS, v2coSS, v1_clipSS, v2_clipSS)) {
2368 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2369 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2373 if ((inside_bucket_flag & (ISECT_2 | ISECT_3)) != (ISECT_2 | ISECT_3)) {
2374 if (line_clip_rect2f(cliprect, bucket_bounds, v2coSS, v3coSS, v1_clipSS, v2_clipSS)) {
2375 if ((inside_bucket_flag & ISECT_2) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2376 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2380 if ((inside_bucket_flag & (ISECT_3 | ISECT_1)) != (ISECT_3 | ISECT_1)) {
2381 if (line_clip_rect2f(cliprect, bucket_bounds, v3coSS, v1coSS, v1_clipSS, v2_clipSS)) {
2382 if ((inside_bucket_flag & ISECT_3) == 0) { copy_v2_v2(isectVCosSS[*tot], v1_clipSS); (*tot)++; }
2383 if ((inside_bucket_flag & ISECT_1) == 0) { copy_v2_v2(isectVCosSS[*tot], v2_clipSS); (*tot)++; }
2388 if ((*tot) < 3) { /* no intersections to speak of */
2393 /* now we have all points we need, collect their angles and sort them clockwise */
2395 for (i = 0; i < (*tot); i++) {
2396 cent[0] += isectVCosSS[i][0];
2397 cent[1] += isectVCosSS[i][1];
2399 cent[0] = cent[0] / (float)(*tot);
2400 cent[1] = cent[1] / (float)(*tot);
2404 /* Collect angles for every point around the center point */
2407 #if 0 /* uses a few more cycles then the above loop */
2408 for (i = 0; i < (*tot); i++) {
2409 isectVCosSS[i][2] = angle_2d_clockwise(up, cent, isectVCosSS[i]);
2413 /* Abuse this var for the loop below */
2414 v1_clipSS[0] = cent[0];
2415 v1_clipSS[1] = cent[1] + 1.0f;
2417 for (i = 0; i < (*tot); i++) {
2418 v2_clipSS[0] = isectVCosSS[i][0] - cent[0];
2419 v2_clipSS[1] = isectVCosSS[i][1] - cent[1];
2420 isectVCosSS[i][2] = atan2f(v1_clipSS[0] * v2_clipSS[1] - v1_clipSS[1] * v2_clipSS[0],
2421 v1_clipSS[0] * v2_clipSS[0] + v1_clipSS[1] * v2_clipSS[1]);
2424 if (flip) qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort_flip);
2425 else qsort(isectVCosSS, *tot, sizeof(float) * 3, float_z_sort);
2428 while (doubles == true) {
2431 for (i = 0; i < (*tot); i++) {
2432 if (fabsf(isectVCosSS[(i + 1) % *tot][0] - isectVCosSS[i][0]) < PROJ_PIXEL_TOLERANCE &&
2433 fabsf(isectVCosSS[(i + 1) % *tot][1] - isectVCosSS[i][1]) < PROJ_PIXEL_TOLERANCE)
2436 for (j = i; j < (*tot) - 1; j++) {
2437 isectVCosSS[j][0] = isectVCosSS[j + 1][0];
2438 isectVCosSS[j][1] = isectVCosSS[j + 1][1];
2440 /* keep looking for more doubles */
2446 /* its possible there is only a few left after remove doubles */
2448 // printf("removed too many doubles B\n");
2455 for (i = 0; i < (*tot); i++) {
2456 barycentric_weights_v2(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2457 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2461 for (i = 0; i < (*tot); i++) {
2462 barycentric_weights_v2_persp(v1coSS, v2coSS, v3coSS, isectVCosSS[i], w);
2463 interp_v2_v2v2v2(bucket_bounds_uv[i], uv1co, uv2co, uv3co, w);
2468 #ifdef PROJ_DEBUG_PRINT_CLIP
2469 /* include this at the bottom of the above function to debug the output */
2472 /* If there are ever any problems, */
2473 float test_uv[4][2];
2475 if (is_ortho) rect_to_uvspace_ortho(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2476 else rect_to_uvspace_persp(bucket_bounds, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, test_uv, flip);
2477 printf("( [(%f,%f), (%f,%f), (%f,%f), (%f,%f)], ",
2478 test_uv[0][0], test_uv[0][1], test_uv[1][0], test_uv[1][1],
2479 test_uv[2][0], test_uv[2][1], test_uv[3][0], test_uv[3][1]);
2481 printf(" [(%f,%f), (%f,%f), (%f,%f)], ", uv1co[0], uv1co[1], uv2co[0], uv2co[1], uv3co[0], uv3co[1]);
2484 for (i = 0; i < (*tot); i++) {
2485 printf("(%f, %f),", bucket_bounds_uv[i][0], bucket_bounds_uv[i][1]);
2493 * # This script creates faces in a blender scene from printed data above.
2496 * ...(output from above block)...
2499 * from Blender import Scene, Mesh, Window, sys, Mathutils
2503 * V = Mathutils.Vector
2506 * sce = bpy.data.scenes.active
2508 * for item in project_ls:
2513 * me = bpy.data.meshes.new()
2514 * ob = sce.objects.new(me)
2516 * me.verts.extend([V(bb[0]).xyz, V(bb[1]).xyz, V(bb[2]).xyz, V(bb[3]).xyz])
2517 * me.faces.extend([(0,1,2,3),])
2518 * me.verts.extend([V(uv[0]).xyz, V(uv[1]).xyz, V(uv[2]).xyz])
2519 * me.faces.extend([(4,5,6),])
2521 * vs = [V(p).xyz for p in poly]
2524 * me.verts.extend(vs)
2527 * while i < len(me.verts):
2529 * if ii == len(me.verts):
2531 * me.edges.extend([i, ii])
2534 * if __name__ == '__main__':
2547 /* checks if pt is inside a convex 2D polyline, the polyline must be ordered rotating clockwise
2548 * otherwise it would have to test for mixed (line_point_side_v2 > 0.0f) cases */
2549 static bool IsectPoly2Df(const float pt[2], float uv[][2], const int tot)
2552 if (line_point_side_v2(uv[tot - 1], uv[0], pt) < 0.0f)
2555 for (i = 1; i < tot; i++) {
2556 if (line_point_side_v2(uv[i - 1], uv[i], pt) < 0.0f)
2563 static bool IsectPoly2Df_twoside(const float pt[2], float uv[][2], const int tot)
2566 bool side = (line_point_side_v2(uv[tot - 1], uv[0], pt) > 0.0f);
2568 for (i = 1; i < tot; i++) {
2569 if ((line_point_side_v2(uv[i - 1], uv[i], pt) > 0.0f) != side)
2577 /* One of the most important function for projection painting,
2578 * since it selects the pixels to be added into each bucket.
2580 * initialize pixels from this face where it intersects with the bucket_index,
2581 * optionally initialize pixels for removing seams */
2582 static void project_paint_face_init(
2583 const ProjPaintState *ps,
2584 const int thread_index, const int bucket_index, const int tri_index, const int image_index,
2585 const rctf *clip_rect, const rctf *bucket_bounds, ImBuf *ibuf, ImBuf **tmpibuf)
2587 /* Projection vars, to get the 3D locations into screen space */
2588 MemArena *arena = ps->arena_mt[thread_index];
2589 LinkNode **bucketPixelNodes = ps->bucketRect + bucket_index;
2590 LinkNode *bucketFaceNodes = ps->bucketFaces[bucket_index];
2591 bool threaded = (ps->thread_tot > 1);
2596 IMAPAINT_TILE_NUMBER(ibuf->x),
2598 ps->projImages + image_index,
2601 const MLoopTri *lt = &ps->mlooptri_eval[tri_index];
2602 const int lt_vtri[3] = { PS_LOOPTRI_AS_VERT_INDEX_3(ps, lt) };
2603 const float *lt_tri_uv[3] = { PS_LOOPTRI_AS_UV_3(ps->poly_to_loop_uv, lt) };
2605 /* UV/pixel seeking data */
2606 /* Image X/Y-Pixel */
2609 /* Image floating point UV - same as x, y but from 0.0-1.0 */
2612 /* vert co screen-space, these will be assigned to lt_vtri[0-2] */
2613 const float *v1coSS, *v2coSS, *v3coSS;
2615 /* vertex screenspace coords */
2616 const float *vCo[3];
2620 /* for convenience only, these will be assigned to lt_tri_uv[0],1,2 or lt_tri_uv[0],2,3 */
2621 float *uv1co, *uv2co, *uv3co;
2622 float pixelScreenCo[4];
2623 bool do_3d_mapping = ps->brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D;
2627 /* vars for getting uvspace bounds */
2629 /* bucket bounds in UV space so we can init pixels only for this face, */
2630 float lt_uv_pxoffset[3][2];
2631 float xhalfpx, yhalfpx;
2632 const float ibuf_xf = (float)ibuf->x, ibuf_yf = (float)ibuf->y;
2634 /* for early loop exit */
2635 int has_x_isect = 0, has_isect = 0;
2637 float uv_clip[8][2];
2639 const bool is_ortho = ps->is_ortho;
2640 const bool is_flip_object = ps->is_flip_object;
2641 const bool do_backfacecull = ps->do_backfacecull;
2642 const bool do_clip = ps->rv3d ? ps->rv3d->rflag & RV3D_CLIPPING : 0;
2644 vCo[0] = ps->mvert_eval[lt_vtri[0]].co;
2645 vCo[1] = ps->mvert_eval[lt_vtri[1]].co;
2646 vCo[2] = ps->mvert_eval[lt_vtri[2]].co;
2649 /* Use lt_uv_pxoffset instead of lt_tri_uv so we can offset the UV half a pixel
2650 * this is done so we can avoid offsetting all the pixels by 0.5 which causes
2651 * problems when wrapping negative coords */
2652 xhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 3.0f))) / ibuf_xf;
2653 yhalfpx = (0.5f + (PROJ_PIXEL_TOLERANCE * (1.0f / 4.0f))) / ibuf_yf;
2655 /* Note about (PROJ_GEOM_TOLERANCE/x) above...
2656 * Needed to add this offset since UV coords are often quads aligned to pixels.
2657 * In this case pixels can be exactly between 2 triangles causing nasty
2660 * This workaround can be removed and painting will still work on most cases
2661 * but since the first thing most people try is painting onto a quad- better make it work.
2664 lt_uv_pxoffset[0][0] = lt_tri_uv[0][0] - xhalfpx;
2665 lt_uv_pxoffset[0][1] = lt_tri_uv[0][1] - yhalfpx;
2667 lt_uv_pxoffset[1][0] = lt_tri_uv[1][0] - xhalfpx;
2668 lt_uv_pxoffset[1][1] = lt_tri_uv[1][1] - yhalfpx;
2670 lt_uv_pxoffset[2][0] = lt_tri_uv[2][0] - xhalfpx;
2671 lt_uv_pxoffset[2][1] = lt_tri_uv[2][1] - yhalfpx;
2674 uv1co = lt_uv_pxoffset[0]; // was lt_tri_uv[i1];
2675 uv2co = lt_uv_pxoffset[1]; // was lt_tri_uv[i2];
2676 uv3co = lt_uv_pxoffset[2]; // was lt_tri_uv[i3];
2678 v1coSS = ps->screenCoords[lt_vtri[0]];
2679 v2coSS = ps->screenCoords[lt_vtri[1]];
2680 v3coSS = ps->screenCoords[lt_vtri[2]];
2682 /* This function gives is a concave polyline in UV space from the clipped tri*/
2683 project_bucket_clip_face(
2684 is_ortho, is_flip_object,
2685 clip_rect, bucket_bounds,
2686 v1coSS, v2coSS, v3coSS,
2687 uv1co, uv2co, uv3co,
2688 uv_clip, &uv_clip_tot,
2689 do_backfacecull || ps->do_occlude);
2691 /* sometimes this happens, better just allow for 8 intersectiosn even though there should be max 6 */
2693 if (uv_clip_tot > 6) {
2694 printf("this should never happen! %d\n", uv_clip_tot);
2698 if (pixel_bounds_array(uv_clip, &bounds_px, ibuf->x, ibuf->y, uv_clip_tot)) {
2700 project_paint_undo_tiles_init(
2701 &bounds_px, ps->projImages + image_index, tmpibuf,
2702 tile_width, threaded, ps->do_masking);
2707 for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2708 //uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2709 /* use pixel offset UV coords instead */
2710 uv[1] = (float)y / ibuf_yf;
2713 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2714 //uv[0] = (((float)x) + 0.5f) / ibuf->x;
2715 /* use pixel offset UV coords instead */
2716 uv[0] = (float)x / ibuf_xf;
2718 /* Note about IsectPoly2Df_twoside, checking the face or uv flipping doesn't work,
2719 * could check the poly direction but better to do this */
2720 if ((do_backfacecull == true && IsectPoly2Df(uv, uv_clip, uv_clip_tot)) ||
2721 (do_backfacecull == false && IsectPoly2Df_twoside(uv, uv_clip, uv_clip_tot)))
2724 has_x_isect = has_isect = 1;
2726 if (is_ortho) screen_px_from_ortho(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2727 else screen_px_from_persp(uv, v1coSS, v2coSS, v3coSS, uv1co, uv2co, uv3co, pixelScreenCo, w);
2729 /* a pity we need to get the worldspace pixel location here */
2730 if (do_clip || do_3d_mapping) {
2733 ps->mvert_eval[lt_vtri[0]].co,
2734 ps->mvert_eval[lt_vtri[1]].co,
2735 ps->mvert_eval[lt_vtri[2]].co,
2737 if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2738 /* Watch out that no code below this needs to run */
2743 /* Is this UV visible from the view? - raytrace */
2744 /* project_paint_PickFace is less complex, use for testing */
2745 //if (project_paint_PickFace(ps, pixelScreenCo, w, &side) == tri_index) {
2746 if ((ps->do_occlude == false) ||
2747 !project_bucket_point_occluded(ps, bucketFaceNodes, tri_index, pixelScreenCo))
2749 mask = project_paint_uvpixel_mask(ps, tri_index, w);
2752 BLI_linklist_prepend_arena(
2754 project_paint_uvpixel_init(
2755 ps, arena, &tinf, x, y, mask, tri_index,
2756 pixelScreenCo, wco, w),
2763 else if (has_x_isect) {
2764 /* assuming the face is not a bow-tie - we know we cant intersect again on the X */
2771 #if 0 /* TODO - investigate why this dosnt work sometimes! it should! */
2772 /* no intersection for this entire row,
2773 * after some intersection above means we can quit now */
2774 if (has_x_isect == 0 && has_isect) {
2783 #ifndef PROJ_DEBUG_NOSEAMBLEED
2784 if (ps->seam_bleed_px > 0.0f) {
2788 /* Other threads could be modifying these vars. */
2789 BLI_thread_lock(LOCK_CUSTOM1);
2792 face_seam_flag = ps->faceSeamFlags[tri_index];
2794 /* are any of our edges un-initialized? */
2795 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_NOSEAM1)) == 0 ||
2796 (face_seam_flag & (PROJ_FACE_SEAM2 | PROJ_FACE_NOSEAM2)) == 0 ||
2797 (face_seam_flag & (PROJ_FACE_SEAM3 | PROJ_FACE_NOSEAM3)) == 0)
2799 project_face_seams_init(ps, tri_index);
2800 face_seam_flag = ps->faceSeamFlags[tri_index];
2801 //printf("seams - %d %d %d %d\n", flag&PROJ_FACE_SEAM1, flag&PROJ_FACE_SEAM2, flag&PROJ_FACE_SEAM3);
2804 if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_SEAM2 | PROJ_FACE_SEAM3)) == 0) {
2807 /* Other threads could be modifying these vars. */
2808 BLI_thread_unlock(LOCK_CUSTOM1);
2813 /* we have a seam - deal with it! */
2815 /* Now create new UV's for the seam face */
2816 float (*outset_uv)[2] = ps->faceSeamUVs[tri_index];
2817 /* inset face coords. NOTE!!! ScreenSace for ortho, Worldspace in perspective view */
2818 float insetCos[3][3];
2820 /* vertex screenspace coords */
2821 const float *vCoSS[3];
2823 /* Store the screenspace coords of the face,
2824 * clipped by the bucket's screen aligned rectangle. */
2825 float bucket_clip_edges[2][2];
2826 float edge_verts_inset_clip[2][3];
2827 /* face edge pairs - loop throuh these:
2828 * ((0,1), (1,2), (2,3), (3,0)) or ((0,1), (1,2), (2,0)) for a tri */
2831 float seam_subsection[4][2];
2834 if (outset_uv[0][0] == FLT_MAX) /* first time initialize */
2836 lt_uv_pxoffset, outset_uv, ps->seam_bleed_px,
2837 ibuf->x, ibuf->y, (ps->faceWindingFlags[tri_index] & PROJ_FACE_WINDING_CW) == 0);
2839 /* ps->faceSeamUVs cant be modified when threading, now this is done we can unlock. */
2841 /* Other threads could be modifying these vars */
2842 BLI_thread_unlock(LOCK_CUSTOM1);
2845 vCoSS[0] = ps->screenCoords[lt_vtri[0]];
2846 vCoSS[1] = ps->screenCoords[lt_vtri[1]];
2847 vCoSS[2] = ps->screenCoords[lt_vtri[2]];
2849 /* PROJ_FACE_SCALE_SEAM must be slightly less then 1.0f */
2851 scale_tri(insetCos, vCoSS, PROJ_FACE_SCALE_SEAM);
2854 scale_tri(insetCos, vCo, PROJ_FACE_SCALE_SEAM);
2857 for (fidx1 = 0; fidx1 < 3; fidx1++) {
2858 /* next fidx in the face (0,1,2) -> (1,2,0) */
2859 fidx2 = (fidx1 == 2) ? 0 : fidx1 + 1;
2861 if ((face_seam_flag & (1 << fidx1)) && /* 1<<fidx1 -> PROJ_FACE_SEAM# */
2862 line_clip_rect2f(clip_rect, bucket_bounds, vCoSS[fidx1], vCoSS[fidx2], bucket_clip_edges[0], bucket_clip_edges[1]))
2864 /* Avoid div by zero. */
2865 if (len_squared_v2v2(vCoSS[fidx1], vCoSS[fidx2]) > FLT_EPSILON) {
2868 fac1 = line_point_factor_v2(bucket_clip_edges[0], vCoSS[fidx1], vCoSS[fidx2]);
2869 fac2 = line_point_factor_v2(bucket_clip_edges[1], vCoSS[fidx1], vCoSS[fidx2]);
2872 fac1 = screen_px_line_point_factor_v2_persp(ps, bucket_clip_edges[0], vCo[fidx1], vCo[fidx2]);
2873 fac2 = screen_px_line_point_factor_v2_persp(ps, bucket_clip_edges[1], vCo[fidx1], vCo[fidx2]);
2876 interp_v2_v2v2(seam_subsection[0], lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], fac1);
2877 interp_v2_v2v2(seam_subsection[1], lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], fac2);
2879 interp_v2_v2v2(seam_subsection[2], outset_uv[fidx1], outset_uv[fidx2], fac2);
2880 interp_v2_v2v2(seam_subsection[3], outset_uv[fidx1], outset_uv[fidx2], fac1);
2882 /* if the bucket_clip_edges values Z values was kept we could avoid this
2883 * Inset needs to be added so occlusion tests wont hit adjacent faces */
2884 interp_v3_v3v3(edge_verts_inset_clip[0], insetCos[fidx1], insetCos[fidx2], fac1);
2885 interp_v3_v3v3(edge_verts_inset_clip[1], insetCos[fidx1], insetCos[fidx2], fac2);
2888 if (pixel_bounds_uv(seam_subsection, &bounds_px, ibuf->x, ibuf->y)) {
2889 /* bounds between the seam rect and the uvspace bucket pixels */
2892 for (y = bounds_px.ymin; y < bounds_px.ymax; y++) {
2893 // uv[1] = (((float)y) + 0.5f) / (float)ibuf->y;
2894 /* use offset uvs instead */
2895 uv[1] = (float)y / ibuf_yf;
2898 for (x = bounds_px.xmin; x < bounds_px.xmax; x++) {
2899 //uv[0] = (((float)x) + 0.5f) / (float)ibuf->x;
2900 /* use offset uvs instead */
2901 uv[0] = (float)x / ibuf_xf;
2903 /* test we're inside uvspace bucket and triangle bounds */
2904 if (isect_point_quad_v2(uv, UNPACK4(seam_subsection))) {
2907 /* We need to find the closest point along the face edge,
2908 * getting the screen_px_from_*** wont work because our
2909 * actual location is not relevant, since we are outside
2910 * the face, Use VecLerpf to find our location on the side
2911 * of the face's UV */
2913 if (is_ortho) screen_px_from_ortho(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2914 else screen_px_from_persp(ps, uv, v1co, v2co, v3co, uv1co, uv2co, uv3co, pixelScreenCo);
2917 /* Since this is a seam we need to work out where on
2918 * the line this pixel is */
2919 //fac = line_point_factor_v2(uv, uv_seam_quad[0], uv_seam_quad[1]);
2920 fac = resolve_quad_u_v2(uv, UNPACK4(seam_subsection));
2921 interp_v3_v3v3(pixelScreenCo, edge_verts_inset_clip[0], edge_verts_inset_clip[1], fac);
2924 pixelScreenCo[3] = 1.0f;
2925 /* cast because of const */
2926 mul_m4_v4((float(*)[4])ps->projectMat, pixelScreenCo);
2927 pixelScreenCo[0] = (float)(ps->winx * 0.5f) + (ps->winx * 0.5f) * pixelScreenCo[0] / pixelScreenCo[3];
2928 pixelScreenCo[1] = (float)(ps->winy * 0.5f) + (ps->winy * 0.5f) * pixelScreenCo[1] / pixelScreenCo[3];
2929 /* Use the depth for bucket point occlusion */
2930 pixelScreenCo[2] = pixelScreenCo[2] / pixelScreenCo[3];
2933 if ((ps->do_occlude == false) ||
2934 !project_bucket_point_occluded(ps, bucketFaceNodes, tri_index, pixelScreenCo))
2936 /* Only bother calculating the weights if we intersect */
2937 if (ps->do_mask_normal || ps->poly_to_loop_uv_clone) {
2938 const float uv_fac = fac1 + (fac * (fac2 - fac1));
2940 /* get the UV on the line since we want to copy the
2941 * pixels from there for bleeding */
2943 interp_v2_v2v2(uv_close, lt_uv_pxoffset[fidx1], lt_uv_pxoffset[fidx2], uv_fac);
2944 barycentric_weights_v2(lt_uv_pxoffset[0], lt_uv_pxoffset[1], lt_uv_pxoffset[2], uv_close, w);
2947 /* Cheat, we know where we are along the edge
2948 * so work out the weights from that */
2949 w[0] = w[1] = w[2] = 0.0;
2950 w[fidx1] = 1.0f - uv_fac;
2955 /* a pity we need to get the worldspace
2956 * pixel location here */
2957 if (do_clip || do_3d_mapping) {
2958 interp_v3_v3v3v3(wco, vCo[0], vCo[1], vCo[2], w);
2960 if (do_clip && ED_view3d_clipping_test(ps->rv3d, wco, true)) {
2961 /* Watch out that no code below
2962 * this needs to run */