2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2007 Blender Foundation.
19 * All rights reserved.
22 * Contributor(s): Joseph Eagar, Joshua Leung, Howard Trickey,
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/editors/mesh/editmesh_knife.c
33 # define _USE_MATH_DEFINES
36 #include "MEM_guardedalloc.h"
38 #include "BLI_listbase.h"
39 #include "BLI_string.h"
40 #include "BLI_array.h"
41 #include "BLI_alloca.h"
42 #include "BLI_linklist.h"
44 #include "BLI_smallhash.h"
45 #include "BLI_memarena.h"
47 #include "BLF_translation.h"
49 #include "BKE_DerivedMesh.h"
50 #include "BKE_context.h"
51 #include "BKE_editmesh.h"
52 #include "BKE_editmesh_bvh.h"
55 #include "BIF_glutil.h" /* for paint cursor */
57 #include "ED_screen.h"
58 #include "ED_space_api.h"
59 #include "ED_view3d.h"
65 #include "DNA_object_types.h"
66 #include "UI_resources.h"
68 #include "RNA_access.h"
69 #include "RNA_define.h"
71 #include "mesh_intern.h" /* own include */
73 /* this code here is kindof messy. . .I might need to eventually rework it - joeedh */
75 #define KMAXDIST 10 /* max mouse distance from edge before not detecting it */
77 #define KNIFE_FLT_EPS 0.00001f
78 #define KNIFE_FLT_EPS_SQUARED (KNIFE_FLT_EPS * KNIFE_FLT_EPS)
80 typedef struct KnifeColors {
81 unsigned char line[3];
82 unsigned char edge[3];
83 unsigned char curpoint[3];
84 unsigned char curpoint_a[4];
85 unsigned char point[3];
86 unsigned char point_a[4];
89 /* knifetool operator */
90 typedef struct KnifeVert {
91 BMVert *v; /* non-NULL if this is an original vert */
95 float co[3], cageco[3], sco[2]; /* sco is screen coordinates for cageco */
96 bool is_face, in_space;
101 struct Ref *next, *prev;
105 typedef struct KnifeEdge {
107 BMFace *basef; /* face to restrict face fill to */
110 BMEdge *e /* , *e_old */; /* non-NULL if this is an original edge */
114 typedef struct BMEdgeHit {
116 float hit[3], cagehit[3];
117 float realhit[3]; /* used in midpoint mode */
119 float l; /* lambda along cut line */
120 float perc; /* lambda along hit line */
121 KnifeVert *v; /* set if snapped to a vert */
125 typedef struct KnifePosData {
129 /* At most one of vert, edge, or bmface should be non-NULL,
130 * saying whether the point is snapped to a vertex, edge, or in a face.
131 * If none are set, this point is in space and is_space should be true. */
137 float mval[2]; /* mouse screen position (may be non-integral if snapped to something) */
140 /* struct for properties used while drawing */
141 typedef struct KnifeTool_OpData {
142 ARegion *ar; /* region that knifetool was activated in */
143 void *draw_handle; /* for drawing preview loop */
144 ViewContext vc; /* note: _don't_ use 'mval', instead use the one we define below */
145 float mval[2]; /* mouse value with snapping applied */
166 /* used for drag-cutting */
170 /* Data for mouse-position-derived data (cur) and previous click (prev) */
171 KnifePosData curr, prev;
173 int totkedge, totkvert;
181 /* run by the UI or not */
184 /* operatpr options */
185 bool cut_through; /* preference, can be modified at runtime (that feature may go) */
186 bool only_select; /* set on initialization */
187 bool select_result; /* set on initialization */
191 float clipsta, clipend;
201 bool snap_midpoints, extend;
202 bool ignore_edge_snapping;
203 bool ignore_vert_snapping;
213 const float (*cagecos)[3];
216 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f);
219 static void knife_input_ray_cast(KnifeTool_OpData *kcd, const float mval[2],
220 float r_origin[3], float r_ray[3]);
222 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const float mval[2], const float ofs,
223 float r_origin[3], float r_dest[3]);
225 static void knife_update_header(bContext *C, KnifeTool_OpData *kcd)
227 #define HEADER_LENGTH 256
228 char header[HEADER_LENGTH];
230 BLI_snprintf(header, HEADER_LENGTH, IFACE_("LMB: define cut lines, Return/Spacebar: confirm, Esc or RMB: cancel, "
231 "E: new cut, Ctrl: midpoint snap (%s), Shift: ignore snap (%s), "
232 "C: angle constrain (%s), Z: cut through (%s)"),
233 kcd->snap_midpoints ? IFACE_("On") : IFACE_("Off"),
234 kcd->ignore_edge_snapping ? IFACE_("On") : IFACE_("Off"),
235 kcd->angle_snapping ? IFACE_("On") : IFACE_("Off"),
236 kcd->cut_through ? IFACE_("On") : IFACE_("Off"));
238 ED_area_headerprint(CTX_wm_area(C), header);
242 BLI_INLINE int round_ftoi(float x)
244 return x > 0.0f ? (int)(x + 0.5f) : (int)(x - 0.5f);
248 static void knife_project_v2(const KnifeTool_OpData *kcd, const float co[3], float sco[2])
250 ED_view3d_project_float_v2_m4(kcd->ar, co, sco, (float (*)[4])kcd->projmat);
253 static void knife_pos_data_clear(KnifePosData *kpd)
263 static ListBase *knife_empty_list(KnifeTool_OpData *kcd)
267 lst = BLI_memarena_alloc(kcd->arena, sizeof(ListBase));
268 lst->first = lst->last = NULL;
272 static void knife_append_list(KnifeTool_OpData *kcd, ListBase *lst, void *elem)
276 ref = BLI_mempool_calloc(kcd->refs);
278 BLI_addtail(lst, ref);
281 static Ref *find_ref(ListBase *lb, void *ref)
285 for (ref1 = lb->first; ref1; ref1 = ref1->next) {
286 if (ref1->ref == ref)
293 static KnifeEdge *new_knife_edge(KnifeTool_OpData *kcd)
296 return BLI_mempool_calloc(kcd->kedges);
299 static void knife_add_to_vert_edges(KnifeTool_OpData *kcd, KnifeEdge *kfe)
301 knife_append_list(kcd, &kfe->v1->edges, kfe);
302 knife_append_list(kcd, &kfe->v2->edges, kfe);
305 /* Add faces of an edge to a KnifeVert's faces list. No checks for dups. */
306 static void knife_add_edge_faces_to_vert(KnifeTool_OpData *kcd, KnifeVert *kfv, BMEdge *e)
311 BM_ITER_ELEM (f, &bmiter, e, BM_FACES_OF_EDGE) {
312 knife_append_list(kcd, &kfv->faces, f);
316 /* Find a face in common in the two faces lists.
317 * If more than one, return the first; if none, return NULL */
318 static BMFace *knife_find_common_face(ListBase *faces1, ListBase *faces2)
322 for (ref1 = faces1->first; ref1; ref1 = ref1->next) {
323 for (ref2 = faces2->first; ref2; ref2 = ref2->next) {
324 if (ref1->ref == ref2->ref)
325 return (BMFace *)(ref1->ref);
331 static KnifeVert *new_knife_vert(KnifeTool_OpData *kcd, const float co[3], const float cageco[3])
333 KnifeVert *kfv = BLI_mempool_calloc(kcd->kverts);
337 copy_v3_v3(kfv->co, co);
338 copy_v3_v3(kfv->cageco, cageco);
340 knife_project_v2(kcd, kfv->co, kfv->sco);
345 /* get a KnifeVert wrapper for an existing BMVert */
346 static KnifeVert *get_bm_knife_vert(KnifeTool_OpData *kcd, BMVert *v)
348 KnifeVert *kfv = BLI_ghash_lookup(kcd->origvertmap, v);
354 kfv = new_knife_vert(kcd, v->co, kcd->cagecos[BM_elem_index_get(v)]);
356 BLI_ghash_insert(kcd->origvertmap, v, kfv);
357 BM_ITER_ELEM (f, &bmiter, v, BM_FACES_OF_VERT) {
358 knife_append_list(kcd, &kfv->faces, f);
365 /* get a KnifeEdge wrapper for an existing BMEdge */
366 static KnifeEdge *get_bm_knife_edge(KnifeTool_OpData *kcd, BMEdge *e)
368 KnifeEdge *kfe = BLI_ghash_lookup(kcd->origedgemap, e);
373 kfe = new_knife_edge(kcd);
375 kfe->v1 = get_bm_knife_vert(kcd, e->v1);
376 kfe->v2 = get_bm_knife_vert(kcd, e->v2);
378 knife_add_to_vert_edges(kcd, kfe);
380 BLI_ghash_insert(kcd->origedgemap, e, kfe);
382 BM_ITER_ELEM (f, &bmiter, e, BM_FACES_OF_EDGE) {
383 knife_append_list(kcd, &kfe->faces, f);
390 /* User has just clicked for first time or first time after a restart (E key).
391 * Copy the current position data into prev. */
392 static void knife_start_cut(KnifeTool_OpData *kcd)
394 kcd->prev = kcd->curr;
395 kcd->curr.is_space = 0; /*TODO: why do we do this? */
397 if (kcd->prev.vert == NULL && kcd->prev.edge == NULL && is_zero_v3(kcd->prev.cage)) {
398 /* Make prevcage a point on the view ray to mouse closest to a point on model: choose vertex 0 */
399 float origin[3], origin_ofs[3];
402 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
403 v0 = BM_vert_at_index(kcd->em->bm, 0);
405 closest_to_line_v3(kcd->prev.cage, v0->co, origin_ofs, origin);
406 copy_v3_v3(kcd->prev.co, kcd->prev.cage); /*TODO: do we need this? */
407 copy_v3_v3(kcd->curr.cage, kcd->prev.cage);
408 copy_v3_v3(kcd->curr.co, kcd->prev.co);
413 static ListBase *knife_get_face_kedges(KnifeTool_OpData *kcd, BMFace *f)
415 ListBase *lst = BLI_ghash_lookup(kcd->kedgefacemap, f);
421 lst = knife_empty_list(kcd);
423 BM_ITER_ELEM (e, &bmiter, f, BM_EDGES_OF_FACE) {
424 knife_append_list(kcd, lst, get_bm_knife_edge(kcd, e));
427 BLI_ghash_insert(kcd->kedgefacemap, f, lst);
433 /* finds the proper face to restrict face fill to */
434 static void knife_find_basef(KnifeEdge *kfe)
436 kfe->basef = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
439 static void knife_edge_append_face(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMFace *f)
441 knife_append_list(kcd, knife_get_face_kedges(kcd, f), kfe);
442 knife_append_list(kcd, &kfe->faces, f);
445 static KnifeVert *knife_split_edge(KnifeTool_OpData *kcd, KnifeEdge *kfe, float co[3], KnifeEdge **newkfe_out)
447 KnifeEdge *newkfe = new_knife_edge(kcd);
450 float perc, cageco[3], l12;
452 l12 = len_v3v3(kfe->v1->co, kfe->v2->co);
453 if (l12 < KNIFE_FLT_EPS) {
454 copy_v3_v3(cageco, kfe->v1->cageco);
457 perc = len_v3v3(co, kfe->v1->co) / l12;
458 interp_v3_v3v3(cageco, kfe->v1->cageco, kfe->v2->cageco, perc);
461 newkfe->v1 = kfe->v1;
462 newkfe->v2 = new_knife_vert(kcd, co, cageco);
463 newkfe->v2->draw = 1;
465 knife_add_edge_faces_to_vert(kcd, newkfe->v2, kfe->e);
468 /* kfe cuts across an existing face.
469 * If v1 and v2 are in multiple faces together (e.g., if they
470 * are in doubled polys) then this arbitrarily chooses one of them */
471 f = knife_find_common_face(&kfe->v1->faces, &kfe->v2->faces);
473 knife_append_list(kcd, &newkfe->v2->faces, f);
475 newkfe->basef = kfe->basef;
477 ref = find_ref(&kfe->v1->edges, kfe);
478 BLI_remlink(&kfe->v1->edges, ref);
480 kfe->v1 = newkfe->v2;
481 BLI_addtail(&kfe->v1->edges, ref);
483 for (ref = kfe->faces.first; ref; ref = ref->next)
484 knife_edge_append_face(kcd, newkfe, ref->ref);
486 knife_add_to_vert_edges(kcd, newkfe);
488 newkfe->draw = kfe->draw;
491 *newkfe_out = newkfe;
496 /* Make a single KnifeEdge for cut from kcd->prev to kcd->curr.
497 * and move cur data to prev. */
498 static void knife_add_single_cut(KnifeTool_OpData *kcd)
500 KnifeEdge *kfe = new_knife_edge(kcd), *kfe2 = NULL, *kfe3 = NULL;
502 if ((kcd->prev.vert && kcd->prev.vert == kcd->curr.vert) ||
503 (kcd->prev.edge && kcd->prev.edge == kcd->curr.edge))
505 kcd->prev = kcd->curr;
511 if (kcd->prev.vert) {
512 kfe->v1 = kcd->prev.vert;
514 else if (kcd->prev.edge) {
515 kfe->v1 = knife_split_edge(kcd, kcd->prev.edge, kcd->prev.co, &kfe2);
518 kfe->v1 = new_knife_vert(kcd, kcd->prev.co, kcd->prev.co);
519 kfe->v1->draw = kfe->draw = !kcd->prev.is_space;
520 kfe->v1->in_space = kcd->prev.is_space;
521 kfe->draw = !kcd->prev.is_space;
522 kfe->v1->is_face = true;
523 if (kfe->v1->draw && kcd->prev.bmface)
524 knife_append_list(kcd, &kfe->v1->faces, kcd->prev.bmface);
527 if (kcd->curr.vert) {
528 kfe->v2 = kcd->curr.vert;
530 else if (kcd->curr.edge) {
531 kfe->v2 = knife_split_edge(kcd, kcd->curr.edge, kcd->curr.co, &kfe3);
532 kcd->curr.vert = kfe->v2;
535 kfe->v2 = new_knife_vert(kcd, kcd->curr.co, kcd->curr.co);
536 kfe->v2->draw = !kcd->curr.is_space;
537 kfe->v2->is_face = true;
538 kfe->v2->in_space = kcd->curr.is_space;
539 if (kfe->v2->draw && kcd->curr.bmface)
540 knife_append_list(kcd, &kfe->v2->faces, kcd->curr.bmface);
542 if (kcd->curr.is_space)
545 kcd->curr.vert = kfe->v2;
548 knife_find_basef(kfe);
550 knife_add_to_vert_edges(kcd, kfe);
552 if (kfe->basef && !find_ref(&kfe->faces, kfe->basef))
553 knife_edge_append_face(kcd, kfe, kfe->basef);
555 /* sanity check to make sure we're in the right edge/face lists */
556 if (kcd->curr.bmface) {
557 if (!find_ref(&kfe->faces, kcd->curr.bmface)) {
558 knife_edge_append_face(kcd, kfe, kcd->curr.bmface);
561 if (kcd->prev.bmface && kcd->prev.bmface != kcd->curr.bmface) {
562 if (!find_ref(&kfe->faces, kcd->prev.bmface)) {
563 knife_edge_append_face(kcd, kfe, kcd->prev.bmface);
568 /* set up for next cut */
569 kcd->prev = kcd->curr;
572 static int verge_linehit(const void *vlh1, const void *vlh2)
574 const BMEdgeHit *lh1 = vlh1, *lh2 = vlh2;
576 if (lh1->l < lh2->l) return -1;
577 else if (lh1->l > lh2->l) return 1;
578 else if (lh1->v && lh2->v) {
579 /* want like verts to sort together; just compare pointers */
580 if (lh1->v < lh2->v) return -1;
581 else if (lh1->v > lh2->v) return 1;
587 /* If there's a linehit connected (same face) as testi in range [firsti, lasti], return the first such, else -1.
588 * It also counts as connected if both linehits are snapped to the same vertex.
589 * If testi is out of range, look for connection to f instead, if f is non-NULL */
590 static int find_connected_linehit(KnifeTool_OpData *kcd, int testi, BMFace *f, int firsti, int lasti)
594 for (i = firsti; i <= lasti; i++) {
595 if (testi >= 0 && testi < kcd->totlinehit) {
596 if (knife_find_common_face(&kcd->linehits[testi].kfe->faces,
597 &kcd->linehits[i].kfe->faces))
601 else if (kcd->linehits[testi].v &&
602 kcd->linehits[testi].v == kcd->linehits[i].v)
608 if (find_ref(&kcd->linehits[i].kfe->faces, f))
615 /* Sort in order of distance along cut line.
616 * Remove any successive linehits that are snapped to the same vertex.
617 * If joinfaces, treat hits at same distance as follows: try to find
618 * ordering so that preceding and succeeding hits will share a face.
620 static void knife_sort_linehits(KnifeTool_OpData *kcd, bool joinfaces)
622 int i, j, k, nexti, nsame;
624 qsort(kcd->linehits, kcd->totlinehit, sizeof(BMEdgeHit), verge_linehit);
626 /* Remove duplicated linehits snapped to same vertex */
627 i = j = 0; /* loop copies from j to i */
628 while (j < kcd->totlinehit) {
630 if (kcd->linehits[j].v) {
631 for (k = j + 1; k < kcd->totlinehit; k++) {
632 if (kcd->linehits[k].v != kcd->linehits[j].v)
638 kcd->linehits[i] = kcd->linehits[j];
647 /* for ranges of equal "l", swap if neccesary to make predecessor and
648 * successor faces connected to the linehits at either end of the range */
649 for (i = 0; i < kcd->totlinehit - 1; i = nexti) {
650 for (j = i + 1; j < kcd->totlinehit; j++) {
651 if (fabsf(kcd->linehits[j].l - kcd->linehits[i].l) > KNIFE_FLT_EPS)
658 /* find something connected to predecessor of equal range */
659 k = find_connected_linehit(kcd, i - 1, kcd->prev.bmface, i, j);
662 SWAP(BMEdgeHit, kcd->linehits[i], kcd->linehits[k]);
668 /* find something connected to successor of equal range */
669 k = find_connected_linehit(kcd, j + 1, kcd->curr.bmface, i, j);
670 if (k != -1 && k != j) {
671 SWAP(BMEdgeHit, kcd->linehits[j], kcd->linehits[k]);
674 /* rest of same range doesn't matter because we won't connect them */
679 static void knife_add_single_cut_through(KnifeTool_OpData *kcd, KnifeVert *v1, KnifeVert *v2, BMFace *f)
683 kfenew = new_knife_edge(kcd);
689 knife_add_to_vert_edges(kcd, kfenew);
691 if (!find_ref(&kfenew->faces, f))
692 knife_edge_append_face(kcd, kfenew, f);
696 static void knife_get_vert_faces(KnifeTool_OpData *kcd, KnifeVert *kfv, BMFace *facef, ListBase *lst)
702 if (kfv->is_face && facef) {
703 knife_append_list(kcd, lst, facef);
706 BM_ITER_ELEM (f, &bmiter, kfv->v, BM_FACES_OF_VERT) {
707 knife_append_list(kcd, lst, f);
711 for (r = kfv->faces.first; r; r = r->next) {
712 knife_append_list(kcd, lst, r->ref);
717 static void knife_get_edge_faces(KnifeTool_OpData *kcd, KnifeEdge *kfe, ListBase *lst)
723 BM_ITER_ELEM (f, &bmiter, kfe->e, BM_FACES_OF_EDGE) {
724 knife_append_list(kcd, lst, f);
730 static void copy_hit_from_posdata(BMEdgeHit *lh, KnifePosData *pos, float lambda)
735 copy_v3_v3(lh->hit, pos->co);
736 copy_v3_v3(lh->cagehit, pos->cage);
737 copy_v3_v3(lh->realhit, pos->co);
739 /* perc and schit not used by callers of this function */
742 /* BMESH_TODO: add more functionality to cut-through:
743 * - cutting "in face" (e.g., holes) should cut in all faces, not just visible one
744 * - perhaps improve O(n^2) algorithm used here */
745 static void knife_cut_through(KnifeTool_OpData *kcd)
747 BMEdgeHit *lh, *lh2, *linehits;
749 KnifeEdge *kfe, *kfe2;
750 KnifeVert *v1, *v2, *lastv;
751 ListBase *faces1, *faces2;
752 KnifeEdge **splitkfe;
753 bool needprev, needcurr;
756 if (!kcd->totlinehit) {
757 /* if no linehits then no interesting back face stuff to do */
758 knife_add_single_cut(kcd);
762 /* sort eliminates hits on same vertices */
763 knife_sort_linehits(kcd, false);
765 /* code is cleaner if make prev and curr into hits (if they are on edges or verts) */
767 needprev = ((kcd->prev.vert && kcd->prev.vert != kcd->linehits[0].v) || kcd->prev.edge);
768 needcurr = ((kcd->curr.vert && kcd->curr.vert != kcd->linehits[n - 1].v) || kcd->curr.edge);
769 n += needprev + needcurr;
770 linehits = MEM_callocN(n * sizeof(BMEdgeHit), "knife_cut_through");
773 copy_hit_from_posdata(&linehits[0], &kcd->prev, 0.0f);
776 memcpy(linehits + i, kcd->linehits, kcd->totlinehit * sizeof(BMEdgeHit));
777 i += kcd->totlinehit;
779 copy_hit_from_posdata(&linehits[i], &kcd->curr, 1.0f);
782 splitkfe = MEM_callocN(n * sizeof(KnifeEdge *), "knife_cut_through");
785 for (i = 0, lh = linehits; i < n; i++, lh++) {
789 /* get faces incident on hit lh */
795 faces1 = &kfe->faces;
798 /* For each following hit, connect if lh1 an lh2 share a face */
799 for (j = i + 1, lh2 = lh + 1; j < n; j++, lh2++) {
807 faces2 = &kfe2->faces;
810 f = knife_find_common_face(faces1, faces2);
813 v1 = splitkfe[i] ? kfe->v1 : knife_split_edge(kcd, kfe, lh->hit, &splitkfe[i]);
815 v2 = splitkfe[j] ? kfe2->v1 : knife_split_edge(kcd, kfe2, lh2->hit, &splitkfe[j]);
816 knife_add_single_cut_through(kcd, v1, v2, f);
824 MEM_freeN(kcd->linehits);
825 kcd->linehits = NULL;
828 /* set up for next cut */
829 kcd->curr.vert = lastv;
830 kcd->prev = kcd->curr;
833 /* User has just left-clicked after the first time.
834 * Add all knife cuts implied by line from prev to curr.
835 * If that line crossed edges then kcd->linehits will be non-NULL. */
836 static void knife_add_cut(KnifeTool_OpData *kcd)
838 KnifePosData savcur = kcd->curr;
840 if (kcd->cut_through) {
841 knife_cut_through(kcd);
843 else if (kcd->linehits) {
844 BMEdgeHit *lh, *lastlh, *firstlh;
847 knife_sort_linehits(kcd, true);
850 lastlh = firstlh = NULL;
851 for (i = 0; i < kcd->totlinehit; i++, (lastlh = lh), lh++) {
852 BMFace *f = lastlh ? lastlh->f : lh->f;
854 if (lastlh && len_squared_v3v3(lastlh->hit, lh->hit) == 0.0f) {
859 else if (lastlh && firstlh) {
860 if (firstlh->v || lastlh->v) {
861 KnifeVert *kfv = firstlh->v ? firstlh->v : lastlh->v;
863 kcd->prev.vert = kfv;
864 copy_v3_v3(kcd->prev.co, firstlh->hit);
865 copy_v3_v3(kcd->prev.cage, firstlh->cagehit);
866 kcd->prev.edge = NULL;
867 kcd->prev.bmface = f;
868 /* TODO: should we set prev.in_space = 0 ? */
870 lastlh = firstlh = NULL;
873 if (len_squared_v3v3(kcd->prev.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
875 if (len_squared_v3v3(kcd->curr.cage, lh->realhit) < KNIFE_FLT_EPS_SQUARED)
878 /* first linehit may be down face parallel to view */
879 if (!lastlh && !lh->v && fabsf(lh->l) < KNIFE_FLT_EPS)
882 if (kcd->prev.is_space) {
883 kcd->prev.is_space = 0;
884 copy_v3_v3(kcd->prev.co, lh->hit);
885 copy_v3_v3(kcd->prev.cage, lh->cagehit);
886 kcd->prev.vert = lh->v;
887 kcd->prev.edge = lh->kfe;
888 kcd->prev.bmface = lh->f;
892 kcd->curr.is_space = 0;
893 kcd->curr.edge = lh->kfe;
894 kcd->curr.bmface = lh->f;
895 kcd->curr.vert = lh->v;
896 copy_v3_v3(kcd->curr.co, lh->hit);
897 copy_v3_v3(kcd->curr.cage, lh->cagehit);
899 /* don't draw edges down faces parallel to view */
900 if (lastlh && fabsf(lastlh->l - lh->l) < KNIFE_FLT_EPS) {
901 kcd->prev = kcd->curr;
905 knife_add_single_cut(kcd);
908 if (savcur.is_space) {
913 knife_add_single_cut(kcd);
916 MEM_freeN(kcd->linehits);
917 kcd->linehits = NULL;
921 knife_add_single_cut(kcd);
925 static void knife_finish_cut(KnifeTool_OpData *UNUSED(kcd))
930 static void knifetool_draw_angle_snapping(const KnifeTool_OpData *kcd)
933 double u[3], u1[2], u2[2], v1[3], v2[3], dx, dy;
934 double wminx, wminy, wmaxx, wmaxy;
936 /* make u the window coords of prevcage */
937 view3d_get_transformation(kcd->ar, kcd->vc.rv3d, kcd->ob, &mats);
938 gluProject(kcd->prev.cage[0], kcd->prev.cage[1], kcd->prev.cage[2],
939 mats.modelview, mats.projection, mats.viewport,
940 &u[0], &u[1], &u[2]);
942 /* make u1, u2 the points on window going through u at snap angle */
943 wminx = kcd->ar->winrct.xmin;
944 wmaxx = kcd->ar->winrct.xmin + kcd->ar->winx;
945 wminy = kcd->ar->winrct.ymin;
946 wmaxy = kcd->ar->winrct.ymin + kcd->ar->winy;
948 switch (kcd->angle_snapping) {
952 u1[1] = u2[1] = u[1];
955 u1[0] = u2[0] = u[0];
960 /* clip against left or bottom */
971 /* clip against right or top */
984 /* clip against right or bottom */
995 /* clip against left or top */
1011 /* unproject u1 and u2 back into object space */
1012 gluUnProject(u1[0], u1[1], 0.0,
1013 mats.modelview, mats.projection, mats.viewport,
1014 &v1[0], &v1[1], &v1[2]);
1015 gluUnProject(u2[0], u2[1], 0.0,
1016 mats.modelview, mats.projection, mats.viewport,
1017 &v2[0], &v2[1], &v2[2]);
1019 UI_ThemeColor(TH_TRANSFORM);
1027 static void knife_init_colors(KnifeColors *colors)
1029 /* possible BMESH_TODO: add explicit themes or calculate these by
1030 * figuring out contrasting colors with grid / edges / verts
1031 * a la UI_make_axis_color */
1032 UI_GetThemeColor3ubv(TH_NURB_VLINE, colors->line);
1033 UI_GetThemeColor3ubv(TH_NURB_ULINE, colors->edge);
1034 UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint);
1035 UI_GetThemeColor3ubv(TH_HANDLE_SEL_VECT, colors->curpoint_a);
1036 colors->curpoint_a[3] = 102;
1037 UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point);
1038 UI_GetThemeColor3ubv(TH_ACTIVE_SPLINE, colors->point_a);
1039 colors->point_a[3] = 102;
1042 /* modal loop selection drawing callback */
1043 static void knifetool_draw(const bContext *C, ARegion *UNUSED(ar), void *arg)
1045 View3D *v3d = CTX_wm_view3d(C);
1046 const KnifeTool_OpData *kcd = arg;
1048 if (v3d->zbuf) glDisable(GL_DEPTH_TEST);
1050 glPolygonOffset(1.0f, 1.0f);
1053 glMultMatrixf(kcd->ob->obmat);
1055 if (kcd->mode == MODE_DRAGGING) {
1056 if (kcd->angle_snapping != ANGLE_FREE)
1057 knifetool_draw_angle_snapping(kcd);
1059 glColor3ubv(kcd->colors.line);
1064 glVertex3fv(kcd->prev.cage);
1065 glVertex3fv(kcd->curr.cage);
1071 if (kcd->curr.edge) {
1072 glColor3ubv(kcd->colors.edge);
1076 glVertex3fv(kcd->curr.edge->v1->cageco);
1077 glVertex3fv(kcd->curr.edge->v2->cageco);
1082 else if (kcd->curr.vert) {
1083 glColor3ubv(kcd->colors.point);
1087 glVertex3fv(kcd->curr.cage);
1091 if (kcd->curr.bmface) {
1092 glColor3ubv(kcd->colors.curpoint);
1096 glVertex3fv(kcd->curr.cage);
1100 if (kcd->totlinehit > 0) {
1101 const float vthresh4 = kcd->vthresh / 4.0f;
1102 const float vthresh4_sq = vthresh4 * vthresh4;
1108 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1110 /* draw any snapped verts first */
1111 glColor4ubv(kcd->colors.point_a);
1115 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1116 float sv1[2], sv2[2];
1118 knife_project_v2(kcd, lh->kfe->v1->cageco, sv1);
1119 knife_project_v2(kcd, lh->kfe->v2->cageco, sv2);
1120 knife_project_v2(kcd, lh->cagehit, lh->schit);
1122 if (len_squared_v2v2(lh->schit, sv1) < vthresh4_sq) {
1123 copy_v3_v3(lh->cagehit, lh->kfe->v1->cageco);
1124 glVertex3fv(lh->cagehit);
1125 lh->v = lh->kfe->v1;
1127 else if (len_squared_v2v2(lh->schit, sv2) < vthresh4_sq) {
1128 copy_v3_v3(lh->cagehit, lh->kfe->v2->cageco);
1129 glVertex3fv(lh->cagehit);
1130 lh->v = lh->kfe->v2;
1135 /* now draw the rest */
1136 glColor4ubv(kcd->colors.curpoint_a);
1140 for (i = 0; i < kcd->totlinehit; i++, lh++) {
1141 glVertex3fv(lh->cagehit);
1144 glDisable(GL_BLEND);
1147 if (kcd->totkedge > 0) {
1148 BLI_mempool_iter iter;
1154 BLI_mempool_iternew(kcd->kedges, &iter);
1155 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
1159 glColor3ubv(kcd->colors.line);
1161 glVertex3fv(kfe->v1->cageco);
1162 glVertex3fv(kfe->v2->cageco);
1169 if (kcd->totkvert > 0) {
1170 BLI_mempool_iter iter;
1176 BLI_mempool_iternew(kcd->kverts, &iter);
1177 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
1181 glColor3ubv(kcd->colors.point);
1183 glVertex3fv(kfv->cageco);
1191 if (v3d->zbuf) glEnable(GL_DEPTH_TEST);
1194 static float len_v3_tri_side_max(const float v1[3], const float v2[3], const float v3[3])
1196 const float s1 = len_squared_v3v3(v1, v2);
1197 const float s2 = len_squared_v3v3(v2, v3);
1198 const float s3 = len_squared_v3v3(v3, v1);
1200 return sqrtf(max_fff(s1, s2, s3));
1203 static BMEdgeHit *knife_edge_tri_isect(KnifeTool_OpData *kcd, BMBVHTree *bmtree,
1204 const float v1[3], const float v2[3], const float v3[3],
1205 SmallHash *ehash, bglMats *mats, int *count)
1207 BVHTree *tree2 = BLI_bvhtree_new(3, FLT_EPSILON * 4, 8, 8), *tree = BKE_bmbvh_tree_get(bmtree);
1208 BMEdgeHit *edges = NULL;
1209 BLI_array_declare(edges);
1210 BVHTreeOverlap *results, *result;
1212 float cos[9], tri_norm[3], tri_plane[4], isects[2][3], lambda;
1213 unsigned int tot = 0;
1216 /* for comparing distances, error of intersection depends on triangle scale.
1217 * need to scale down before squaring for accurate comparison */
1218 const float depsilon = (FLT_EPSILON / 2.0f) * len_v3_tri_side_max(v1, v2, v3);
1219 const float depsilon_sq = depsilon * depsilon;
1221 copy_v3_v3(cos + 0, v1);
1222 copy_v3_v3(cos + 3, v2);
1223 copy_v3_v3(cos + 6, v3);
1225 normal_tri_v3(tri_norm, v1, v2, v3);
1226 plane_from_point_normal_v3(tri_plane, v1, tri_norm);
1228 BLI_bvhtree_insert(tree2, 0, cos, 3);
1229 BLI_bvhtree_balance(tree2);
1231 result = results = BLI_bvhtree_overlap(tree, tree2, &tot);
1233 for (i = 0; i < tot; i++, result++) {
1239 ls = (BMLoop **)kcd->em->looptris[result->indexA];
1242 lst = knife_get_face_kedges(kcd, l1->f);
1244 for (ref = lst->first; ref; ref = ref->next) {
1245 KnifeEdge *kfe = ref->ref;
1247 if (BLI_smallhash_haskey(ehash, (uintptr_t)kfe)) {
1248 continue; /* We already found a hit on this knife edge */
1252 if (fabsf(dist_to_plane_v3(kfe->v1->cageco, tri_plane)) < KNIFE_FLT_EPS &&
1253 fabsf(dist_to_plane_v3(kfe->v2->cageco, tri_plane)) < KNIFE_FLT_EPS)
1255 /* both kfe ends are in cutting triangle */
1256 copy_v3_v3(isects[0], kfe->v1->cageco);
1257 copy_v3_v3(isects[1], kfe->v2->cageco);
1260 else if (isect_line_tri_epsilon_v3(kfe->v1->cageco, kfe->v2->cageco, v1, v2, v3, &lambda, NULL, depsilon)) {
1261 /* kfe intersects cutting triangle lambda of the way along kfe */
1262 interp_v3_v3v3(isects[0], kfe->v1->cageco, kfe->v2->cageco, lambda);
1265 for (j = 0; j < n_isects; j++) {
1266 float p[3], no[3], view[3], sp[2];
1268 copy_v3_v3(p, isects[j]);
1269 if (kcd->curr.vert && len_squared_v3v3(kcd->curr.vert->cageco, p) < depsilon_sq) {
1272 if (kcd->prev.vert && len_squared_v3v3(kcd->prev.vert->cageco, p) < depsilon_sq) {
1275 if (len_squared_v3v3(kcd->prev.cage, p) < depsilon_sq ||
1276 len_squared_v3v3(kcd->curr.cage, p) < depsilon_sq)
1280 if ((kcd->vc.rv3d->rflag & RV3D_CLIPPING) &&
1281 ED_view3d_clipping_test(kcd->vc.rv3d, p, true))
1286 knife_project_v2(kcd, p, sp);
1287 ED_view3d_unproject(mats, view, sp[0], sp[1], 0.0f);
1288 mul_m4_v3(kcd->ob->imat, view);
1290 if (kcd->cut_through) {
1294 /* check if this point is visible in the viewport */
1295 float p1[3], lambda1;
1297 /* if face isn't planer, p may be behind the current tesselated tri,
1298 * so move it onto that and then a little towards eye */
1299 if (isect_line_tri_v3(p, view, ls[0]->v->co, ls[1]->v->co, ls[2]->v->co, &lambda1, NULL)) {
1300 interp_v3_v3v3(p1, p, view, lambda1);
1305 sub_v3_v3(view, p1);
1308 copy_v3_v3(no, view);
1309 mul_v3_fl(no, 0.003);
1311 /* go towards view a bit */
1315 f_hit = BKE_bmbvh_ray_cast(bmtree, p1, no, KNIFE_FLT_EPS, NULL, NULL, NULL);
1318 /* ok, if visible add the new point */
1319 if (!f_hit && !BLI_smallhash_haskey(ehash, (uintptr_t)kfe)) {
1322 if (len_squared_v3v3(p, kcd->curr.co) < depsilon_sq ||
1323 len_squared_v3v3(p, kcd->prev.co) < depsilon_sq)
1332 knife_find_basef(kfe);
1334 hit.perc = len_v3v3(p, kfe->v1->cageco) / len_v3v3(kfe->v1->cageco, kfe->v2->cageco);
1335 copy_v3_v3(hit.cagehit, p);
1337 interp_v3_v3v3(p, kfe->v1->co, kfe->v2->co, hit.perc);
1338 copy_v3_v3(hit.realhit, p);
1340 if (kcd->snap_midpoints) {
1341 float perc = hit.perc;
1343 /* select the closest from the edge endpoints or the midpoint */
1347 else if (perc < 0.75f) {
1354 interp_v3_v3v3(hit.hit, kfe->v1->co, kfe->v2->co, perc);
1355 interp_v3_v3v3(hit.cagehit, kfe->v1->cageco, kfe->v2->cageco, perc);
1357 else if (hit.perc < KNIFE_FLT_EPS || hit.perc > 1.0f - KNIFE_FLT_EPS) {
1359 hit.v = (hit.perc < KNIFE_FLT_EPS) ? kfe->v1 : kfe->v2;
1360 copy_v3_v3(hit.hit, hit.v->co);
1361 copy_v3_v3(hit.cagehit, hit.v->co);
1364 copy_v3_v3(hit.hit, p);
1366 knife_project_v2(kcd, hit.cagehit, hit.schit);
1368 BLI_array_append(edges, hit);
1369 BLI_smallhash_insert(ehash, (uintptr_t)kfe, NULL);
1378 BLI_bvhtree_free(tree2);
1379 *count = BLI_array_count(edges);
1384 static void knife_bgl_get_mats(KnifeTool_OpData *UNUSED(kcd), bglMats *mats)
1387 //copy_m4_m4(mats->modelview, kcd->vc.rv3d->viewmat);
1388 //copy_m4_m4(mats->projection, kcd->vc.rv3d->winmat);
1391 /* Calculate maximum excursion from (0,0,0) of mesh */
1392 static void calc_ortho_extent(KnifeTool_OpData *kcd)
1396 BMesh *bm = kcd->em->bm;
1397 float max_xyz = 0.0f;
1400 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
1401 for (i = 0; i < 3; i++)
1402 max_xyz = max_ff(max_xyz, fabs(v->co[i]));
1404 kcd->ortho_extent = max_xyz;
1407 /* Clip the line (v1, v2) to planes perpendicular to it and distances d from
1408 * the closest point on the line to the origin */
1409 static void clip_to_ortho_planes(float v1[3], float v2[3], float d)
1412 const float origin[3] = {0.0f, 0.0f, 0.0f};
1414 closest_to_line_v3(closest, origin, v1, v2);
1415 dist_ensure_v3_v3fl(v1, closest, d);
1416 dist_ensure_v3_v3fl(v2, closest, d);
1419 /* Finds visible (or all, if cutting through) edges that intersects the current screen drag line */
1420 static void knife_find_line_hits(KnifeTool_OpData *kcd)
1424 SmallHash hash, *ehash = &hash;
1425 float v1[3], v2[3], v3[3], v4[4], s1[2], s2[2];
1428 knife_bgl_get_mats(kcd, &mats);
1430 if (kcd->linehits) {
1431 MEM_freeN(kcd->linehits);
1432 kcd->linehits = NULL;
1433 kcd->totlinehit = 0;
1436 copy_v3_v3(v1, kcd->prev.cage);
1437 copy_v3_v3(v2, kcd->curr.cage);
1439 /* project screen line's 3d coordinates back into 2d */
1440 knife_project_v2(kcd, v1, s1);
1441 knife_project_v2(kcd, v2, s2);
1443 if (len_squared_v2v2(s1, s2) < 1)
1446 /* unproject screen line */
1447 ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s1, v1, v3, true);
1448 ED_view3d_win_to_segment(kcd->ar, kcd->vc.v3d, s2, v2, v4, true);
1450 mul_m4_v3(kcd->ob->imat, v1);
1451 mul_m4_v3(kcd->ob->imat, v2);
1452 mul_m4_v3(kcd->ob->imat, v3);
1453 mul_m4_v3(kcd->ob->imat, v4);
1455 /* numeric error, 'v1' -> 'v2', 'v2' -> 'v4' can end up being ~2000 units apart in otho mode
1456 * (from ED_view3d_win_to_segment_clip() above)
1457 * this gives precision error in 'knife_edge_tri_isect', rather then solving properly
1458 * (which may involve using doubles everywhere!),
1459 * limit the distance between these points */
1460 if (kcd->is_ortho) {
1461 if (kcd->ortho_extent == 0.0f)
1462 calc_ortho_extent(kcd);
1463 clip_to_ortho_planes(v1, v3, kcd->ortho_extent + 10.0f);
1464 clip_to_ortho_planes(v2, v4, kcd->ortho_extent + 10.0f);
1467 BLI_smallhash_init(ehash);
1469 /* test two triangles of sceen line's plane */
1470 e1 = knife_edge_tri_isect(kcd, kcd->bmbvh, v1, v2, v3, ehash, &mats, &c1);
1471 e2 = knife_edge_tri_isect(kcd, kcd->bmbvh, v2, v3, v4, ehash, &mats, &c2);
1473 e1 = MEM_reallocN(e1, sizeof(BMEdgeHit) * (c1 + c2));
1474 memcpy(e1 + c1, e2, sizeof(BMEdgeHit) * c2);
1482 kcd->totlinehit = c1 + c2;
1484 /* find position along screen line, used for sorting */
1485 for (i = 0; i < kcd->totlinehit; i++) {
1486 BMEdgeHit *lh = e1 + i;
1488 lh->l = len_v2v2(lh->schit, s1) / len_v2v2(s2, s1);
1491 BLI_smallhash_release(ehash);
1494 /* this works but gives numeric problems [#33400] */
1496 static void knife_input_ray_cast(KnifeTool_OpData *kcd, const float mval[2],
1497 float r_origin[3], float r_ray[3])
1502 knife_bgl_get_mats(kcd, &mats);
1504 /* unproject to find view ray */
1505 ED_view3d_unproject(&mats, r_origin, mval[0], mval[1], 0.0f);
1507 if (kcd->is_ortho) {
1508 negate_v3_v3(r_ray, kcd->vc.rv3d->viewinv[2]);
1511 sub_v3_v3v3(r_ray, r_origin, kcd->vc.rv3d->viewinv[3]);
1513 normalize_v3(r_ray);
1515 /* transform into object space */
1516 invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
1517 copy_m3_m4(imat, kcd->ob->obmat);
1520 mul_m4_v3(kcd->ob->imat, r_origin);
1521 mul_m3_v3(imat, r_ray);
1525 static void knife_input_ray_segment(KnifeTool_OpData *kcd, const float mval[2], const float ofs,
1526 float r_origin[3], float r_origin_ofs[3])
1530 knife_bgl_get_mats(kcd, &mats);
1532 /* unproject to find view ray */
1533 ED_view3d_unproject(&mats, r_origin, mval[0], mval[1], 0.0f);
1534 ED_view3d_unproject(&mats, r_origin_ofs, mval[0], mval[1], ofs);
1536 /* transform into object space */
1537 invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
1539 mul_m4_v3(kcd->ob->imat, r_origin);
1540 mul_m4_v3(kcd->ob->imat, r_origin_ofs);
1543 static BMFace *knife_find_closest_face(KnifeTool_OpData *kcd, float co[3], float cageco[3], bool *is_space)
1546 float dist = KMAXDIST;
1548 float origin_ofs[3];
1551 /* unproject to find view ray */
1552 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1553 sub_v3_v3v3(ray, origin_ofs, origin);
1555 f = BKE_bmbvh_ray_cast(kcd->bmbvh, origin, ray, 0.0f, NULL, co, cageco);
1561 if (kcd->is_interactive) {
1562 /* try to use backbuffer selection method if ray casting failed */
1563 f = EDBM_face_find_nearest(&kcd->vc, &dist);
1565 /* cheat for now; just put in the origin instead
1566 * of a true coordinate on the face.
1567 * This just puts a point 1.0f infront of the view. */
1568 add_v3_v3v3(co, origin, ray);
1575 /* find the 2d screen space density of vertices within a radius. used to scale snapping
1576 * distance for picking edges/verts.*/
1577 static int knife_sample_screen_density(KnifeTool_OpData *kcd, const float radius)
1581 float co[3], cageco[3], sco[2];
1583 BLI_assert(kcd->is_interactive == true);
1585 f = knife_find_closest_face(kcd, co, cageco, &is_space);
1587 if (f && !is_space) {
1588 const float radius_sq = radius * radius;
1594 knife_project_v2(kcd, cageco, sco);
1596 lst = knife_get_face_kedges(kcd, f);
1597 for (ref = lst->first; ref; ref = ref->next) {
1598 KnifeEdge *kfe = ref->ref;
1601 for (i = 0; i < 2; i++) {
1602 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1604 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1606 dis_sq = len_squared_v2v2(kfv->sco, sco);
1607 if (dis_sq < radius_sq) {
1608 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1609 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1626 /* returns snapping distance for edges/verts, scaled by the density of the
1627 * surrounding mesh (in screen space)*/
1628 static float knife_snap_size(KnifeTool_OpData *kcd, float maxsize)
1632 if (kcd->is_interactive) {
1633 density = (float)knife_sample_screen_density(kcd, maxsize * 2.0f);
1642 return min_ff(maxsize / (density * 0.5f), maxsize);
1645 /* p is closest point on edge to the mouse cursor */
1646 static KnifeEdge *knife_find_closest_edge(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr, bool *is_space)
1649 float co[3], cageco[3], sco[2];
1650 float maxdist = knife_snap_size(kcd, kcd->ethresh);
1652 if (kcd->ignore_vert_snapping)
1655 f = knife_find_closest_face(kcd, co, cageco, NULL);
1658 /* set p to co, in case we don't find anything, means a face cut */
1660 copy_v3_v3(cagep, cageco);
1662 kcd->curr.bmface = f;
1665 const float maxdist_sq = maxdist * maxdist;
1666 KnifeEdge *cure = NULL;
1669 float dis_sq, curdis_sq = FLT_MAX;
1671 knife_project_v2(kcd, cageco, sco);
1673 /* look through all edges associated with this face */
1674 lst = knife_get_face_kedges(kcd, f);
1675 for (ref = lst->first; ref; ref = ref->next) {
1676 KnifeEdge *kfe = ref->ref;
1678 /* project edge vertices into screen space */
1679 knife_project_v2(kcd, kfe->v1->cageco, kfe->v1->sco);
1680 knife_project_v2(kcd, kfe->v2->cageco, kfe->v2->sco);
1682 dis_sq = dist_squared_to_line_segment_v2(sco, kfe->v1->sco, kfe->v2->sco);
1683 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1684 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1685 float lambda = line_point_factor_v2(sco, kfe->v1->sco, kfe->v2->sco);
1688 interp_v3_v3v3(vec, kfe->v1->cageco, kfe->v2->cageco, lambda);
1690 if (ED_view3d_clipping_test(kcd->vc.rv3d, vec, true) == 0) {
1706 if (!kcd->ignore_edge_snapping || !(cure->e)) {
1707 KnifeVert *edgesnap = NULL;
1709 if (kcd->snap_midpoints) {
1710 mid_v3_v3v3(p, cure->v1->co, cure->v2->co);
1711 mid_v3_v3v3(cagep, cure->v1->cageco, cure->v2->cageco);
1716 closest_to_line_segment_v3(cagep, cageco, cure->v1->cageco, cure->v2->cageco);
1717 d = len_v3v3(cagep, cure->v1->cageco) / len_v3v3(cure->v1->cageco, cure->v2->cageco);
1718 interp_v3_v3v3(p, cure->v1->co, cure->v2->co, d);
1721 /* update mouse coordinates to the snapped-to edge's screen coordinates
1722 * this is important for angle snap, which uses the previous mouse position */
1723 edgesnap = new_knife_vert(kcd, p, cagep);
1724 kcd->curr.mval[0] = edgesnap->sco[0];
1725 kcd->curr.mval[1] = edgesnap->sco[1];
1742 /* find a vertex near the mouse cursor, if it exists */
1743 static KnifeVert *knife_find_closest_vert(KnifeTool_OpData *kcd, float p[3], float cagep[3], BMFace **fptr,
1747 float co[3], cageco[3], sco[2], maxdist = knife_snap_size(kcd, kcd->vthresh);
1749 if (kcd->ignore_vert_snapping)
1752 f = knife_find_closest_face(kcd, co, cageco, is_space);
1754 /* set p to co, in case we don't find anything, means a face cut */
1756 copy_v3_v3(cagep, p);
1757 kcd->curr.bmface = f;
1760 const float maxdist_sq = maxdist * maxdist;
1763 KnifeVert *curv = NULL;
1764 float dis_sq, curdis_sq = FLT_MAX;
1766 knife_project_v2(kcd, cageco, sco);
1768 lst = knife_get_face_kedges(kcd, f);
1769 for (ref = lst->first; ref; ref = ref->next) {
1770 KnifeEdge *kfe = ref->ref;
1773 for (i = 0; i < 2; i++) {
1774 KnifeVert *kfv = i ? kfe->v2 : kfe->v1;
1776 knife_project_v2(kcd, kfv->cageco, kfv->sco);
1778 dis_sq = len_squared_v2v2(kfv->sco, sco);
1779 if (dis_sq < curdis_sq && dis_sq < maxdist_sq) {
1780 if (kcd->vc.rv3d->rflag & RV3D_CLIPPING) {
1781 if (ED_view3d_clipping_test(kcd->vc.rv3d, kfv->cageco, true) == 0) {
1794 if (!kcd->ignore_vert_snapping || !(curv && curv->v)) {
1799 copy_v3_v3(p, curv->co);
1800 copy_v3_v3(cagep, curv->cageco);
1802 /* update mouse coordinates to the snapped-to vertex's screen coordinates
1803 * this is important for angle snap, which uses the previous mouse position */
1804 kcd->curr.mval[0] = curv->sco[0];
1805 kcd->curr.mval[1] = curv->sco[1];
1824 /* update both kcd->curr.mval and kcd->mval to snap to required angle */
1825 static void knife_snap_angle(KnifeTool_OpData *kcd)
1830 dx = kcd->curr.mval[0] - kcd->prev.mval[0];
1831 dy = kcd->curr.mval[1] - kcd->prev.mval[1];
1832 if (dx == 0.0f && dy == 0.0f)
1836 kcd->angle_snapping = ANGLE_90;
1837 kcd->curr.mval[0] = kcd->prev.mval[0];
1842 if (abs_tan <= 0.4142f) { /* tan(22.5 degrees) = 0.4142 */
1843 kcd->angle_snapping = ANGLE_0;
1844 kcd->curr.mval[1] = kcd->prev.mval[1];
1846 else if (abs_tan < 2.4142f) { /* tan(67.5 degrees) = 2.4142 */
1848 kcd->angle_snapping = ANGLE_45;
1849 kcd->curr.mval[1] = kcd->prev.mval[1] + dx;
1852 kcd->angle_snapping = ANGLE_135;
1853 kcd->curr.mval[1] = kcd->prev.mval[1] - dx;
1857 kcd->angle_snapping = ANGLE_90;
1858 kcd->curr.mval[0] = kcd->prev.mval[0];
1861 copy_v2_v2(kcd->mval, kcd->curr.mval);
1864 /* update active knife edge/vert pointers */
1865 static int knife_update_active(KnifeTool_OpData *kcd)
1867 knife_pos_data_clear(&kcd->curr);
1868 copy_v2_v2(kcd->curr.mval, kcd->mval);
1869 if (kcd->angle_snapping != ANGLE_FREE && kcd->mode == MODE_DRAGGING)
1870 knife_snap_angle(kcd);
1872 /* XXX knife_snap_angle updates the view coordinate mouse values to constrained angles,
1873 * which current mouse values are set to current mouse values are then used
1874 * for vertex and edge snap detection, without regard to the exact angle constraint */
1875 kcd->curr.vert = knife_find_closest_vert(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1877 if (!kcd->curr.vert) {
1878 kcd->curr.edge = knife_find_closest_edge(kcd, kcd->curr.co, kcd->curr.cage, &kcd->curr.bmface, &kcd->curr.is_space);
1881 /* if no hits are found this would normally default to (0, 0, 0) so instead
1882 * get a point at the mouse ray closest to the previous point.
1883 * Note that drawing lines in `free-space` isn't properly supported
1884 * but theres no guarantee (0, 0, 0) has any geometry either - campbell */
1885 if (kcd->curr.vert == NULL && kcd->curr.edge == NULL) {
1887 float origin_ofs[3];
1889 knife_input_ray_segment(kcd, kcd->curr.mval, 1.0f, origin, origin_ofs);
1891 closest_to_line_v3(kcd->curr.cage, kcd->prev.cage, origin_ofs, origin);
1894 if (kcd->mode == MODE_DRAGGING) {
1895 knife_find_line_hits(kcd);
1900 #define SCANFILL_CUTS 0
1905 #define VERT_ON_EDGE 16
1906 #define VERT_ORIG 32
1907 #define FACE_FLIP 64
1908 #define BOUNDARY 128
1909 #define FACE_NEW 256
1911 typedef struct facenet_entry {
1912 struct facenet_entry *next, *prev;
1916 static void rnd_offset_co(RNG *rng, float co[3], float scale)
1920 for (i = 0; i < 3; i++) {
1921 co[i] += (BLI_rng_get_float(rng) - 0.5) * scale;
1925 static void remerge_faces(KnifeTool_OpData *kcd)
1927 BMesh *bm = kcd->em->bm;
1928 SmallHash svisit, *visit = &svisit;
1931 BMFace **stack = NULL;
1932 BLI_array_declare(stack);
1933 BMFace **faces = NULL;
1934 BLI_array_declare(faces);
1938 BMO_op_initf(bm, &bmop, "beautify_fill faces=%ff edges=%Fe", FACE_NEW, BOUNDARY);
1940 BMO_op_exec(bm, &bmop);
1941 BMO_slot_buffer_flag_enable(bm, &bmop, "geom.out", BM_FACE, FACE_NEW);
1943 BMO_op_finish(bm, &bmop);
1945 BLI_smallhash_init(visit);
1946 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1951 if (!BMO_elem_flag_test(bm, f, FACE_NEW))
1954 if (BLI_smallhash_haskey(visit, (uintptr_t)f))
1957 BLI_array_empty(stack);
1958 BLI_array_empty(faces);
1959 BLI_array_append(stack, f);
1960 BLI_smallhash_insert(visit, (uintptr_t)f, NULL);
1963 f2 = BLI_array_pop(stack);
1965 BLI_array_append(faces, f2);
1967 BM_ITER_ELEM (e, &eiter, f2, BM_EDGES_OF_FACE) {
1971 if (BMO_elem_flag_test(bm, e, BOUNDARY))
1974 BM_ITER_ELEM (f3, &fiter, e, BM_FACES_OF_EDGE) {
1975 if (!BMO_elem_flag_test(bm, f3, FACE_NEW))
1977 if (BLI_smallhash_haskey(visit, (uintptr_t)f3))
1980 BLI_smallhash_insert(visit, (uintptr_t)f3, NULL);
1981 BLI_array_append(stack, f3);
1984 } while (BLI_array_count(stack) > 0);
1986 if (BLI_array_count(faces) > 0) {
1987 idx = BM_elem_index_get(faces[0]);
1989 f2 = BM_faces_join(bm, faces, BLI_array_count(faces), true);
1991 BMO_elem_flag_enable(bm, f2, FACE_NEW);
1992 BM_elem_index_set(f2, idx); /* set_dirty! *//* BMESH_TODO, check if this is valid or not */
1996 /* BMESH_TODO, check if the code above validates the indices */
1997 /* bm->elem_index_dirty &= ~BM_FACE; */
1998 bm->elem_index_dirty |= BM_FACE;
2000 BLI_smallhash_release(visit);
2002 BLI_array_free(stack);
2003 BLI_array_free(faces);
2006 /* use edgenet to fill faces. this is a bit annoying and convoluted.*/
2007 static void knifenet_fill_faces(KnifeTool_OpData *kcd)
2009 ScanFillContext sf_ctx;
2010 BMesh *bm = kcd->em->bm;
2012 BLI_mempool_iter iter;
2017 facenet_entry *entry;
2018 ListBase *face_nets = MEM_callocN(sizeof(ListBase) * bm->totface, "face_nets");
2019 BMFace **faces = MEM_callocN(sizeof(BMFace *) * bm->totface, "faces knife");
2020 MemArena *arena = BLI_memarena_new(1 << 16, "knifenet_fill_faces");
2023 int i, j, k = 0, totface = bm->totface;
2026 bmesh_edit_begin(bm, BMO_OPTYPE_FLAG_UNTAN_MULTIRES | BMO_OPTYPE_FLAG_NORMALS_CALC | BMO_OPTYPE_FLAG_SELECT_FLUSH);
2028 /* BMESH_TODO this should be valid now, leaving here until we can ensure this - campbell */
2030 BM_ITER_MESH (f, &bmiter, bm, BM_FACES_OF_MESH) {
2031 BM_elem_index_set(f, i); /* set_inline */
2035 bm->elem_index_dirty &= ~BM_FACE;
2037 BM_ITER_MESH (e, &bmiter, bm, BM_EDGES_OF_MESH) {
2038 BMO_elem_flag_enable(bm, e, BOUNDARY);
2041 /* turn knife verts into real verts, as necessary */
2042 BLI_mempool_iternew(kcd->kverts, &iter);
2043 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
2045 /* shouldn't we be at least copying the normal? - if not some comment here should explain why - campbell */
2046 kfv->v = BM_vert_create(bm, kfv->co, NULL, BM_CREATE_NOP);
2048 BMO_elem_flag_enable(bm, kfv->v, DEL);
2052 BMO_elem_flag_enable(bm, kfv->v, VERT_ORIG);
2055 BMO_elem_flag_enable(bm, kfv->v, MARK);
2058 /* we want to only do changed faces. first, go over new edges and add to
2061 BLI_mempool_iternew(kcd->kedges, &iter);
2062 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2064 if (!kfe->v1 || !kfe->v2 || kfe->v1->inspace || kfe->v2->inspace)
2069 if (kfe->e && kfe->v1->v == kfe->e->v1 && kfe->v2->v == kfe->e->v2) {
2070 kfe->e_old = kfe->e;
2077 kfe->e_old = kfe->e;
2079 BMO_elem_flag_enable(bm, kfe->e, DEL);
2080 BMO_elem_flag_disable(bm, kfe->e, BOUNDARY);
2084 kfe->e = BM_edge_create(bm, kfe->v1->v, kfe->v2->v, NULL, BM_CREATE_NO_DOUBLE);
2085 BMO_elem_flag_enable(bm, kfe->e, BOUNDARY);
2087 for (ref = kfe->faces.first; ref; ref = ref->next) {
2090 entry = BLI_memarena_alloc(arena, sizeof(*entry));
2092 BLI_addtail(face_nets + BM_elem_index_get(f), entry);
2096 /* go over original edges, and add to faces with new geometry */
2097 BLI_mempool_iternew(kcd->kedges, &iter);
2098 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2101 if (!kfe->v1 || !kfe->v2 || kfe->v1->inspace || kfe->v2->inspace)
2103 if (!(kfe->e_old && kfe->v1->v == kfe->e_old->v1 && kfe->v2->v == kfe->e_old->v2))
2108 BMO_elem_flag_enable(bm, kfe->e, BOUNDARY);
2109 kfe->e_old = kfe->e;
2111 for (ref = kfe->faces.first; ref; ref = ref->next) {
2114 if (face_nets[BM_elem_index_get(f)].first) {
2115 entry = BLI_memarena_alloc(arena, sizeof(*entry));
2117 BLI_addtail(face_nets + BM_elem_index_get(f), entry);
2122 rng = BLI_rng_new(0);
2124 for (i = 0; i < totface; i++) {
2125 SmallHash *hash = &shash;
2126 ScanFillFace *sf_tri;
2127 ScanFillVert *sf_vert, *sf_vert_last;
2129 float rndscale = (KNIFE_FLT_EPS / 4.0f);
2132 BLI_smallhash_init(hash);
2134 if (face_nets[i].first)
2135 BMO_elem_flag_enable(bm, f, DEL);
2137 BLI_scanfill_begin(&sf_ctx);
2139 for (entry = face_nets[i].first; entry; entry = entry->next) {
2140 if (!BLI_smallhash_haskey(hash, (uintptr_t)entry->kfe->v1)) {
2141 sf_vert = BLI_scanfill_vert_add(&sf_ctx, entry->kfe->v1->v->co);
2142 sf_vert->poly_nr = 0;
2143 rnd_offset_co(rng, sf_vert->co, rndscale);
2144 sf_vert->tmp.p = entry->kfe->v1->v;
2145 BLI_smallhash_insert(hash, (uintptr_t)entry->kfe->v1, sf_vert);
2148 if (!BLI_smallhash_haskey(hash, (uintptr_t)entry->kfe->v2)) {
2149 sf_vert = BLI_scanfill_vert_add(&sf_ctx, entry->kfe->v2->v->co);
2150 sf_vert->poly_nr = 0;
2151 rnd_offset_co(rng, sf_vert->co, rndscale);
2152 sf_vert->tmp.p = entry->kfe->v2->v;
2153 BLI_smallhash_insert(hash, (uintptr_t)entry->kfe->v2, sf_vert);
2157 for (j = 0, entry = face_nets[i].first; entry; entry = entry->next, j++) {
2158 sf_vert_last = BLI_smallhash_lookup(hash, (uintptr_t)entry->kfe->v1);
2159 sf_vert = BLI_smallhash_lookup(hash, (uintptr_t)entry->kfe->v2);
2162 sf_vert_last->poly_nr++;
2165 for (j = 0, entry = face_nets[i].first; entry; entry = entry->next, j++) {
2166 sf_vert_last = BLI_smallhash_lookup(hash, (uintptr_t)entry->kfe->v1);
2167 sf_vert = BLI_smallhash_lookup(hash, (uintptr_t)entry->kfe->v2);
2169 if (sf_vert->poly_nr > 1 && sf_vert_last->poly_nr > 1) {
2170 ScanFillEdge *sf_edge;
2171 sf_edge = BLI_scanfill_edge_add(&sf_ctx, sf_vert_last, sf_vert);
2172 if (entry->kfe->e_old)
2173 sf_edge->f = SF_EDGE_BOUNDARY; /* mark as original boundary edge */
2175 BMO_elem_flag_disable(bm, entry->kfe->e->v1, DEL);
2176 BMO_elem_flag_disable(bm, entry->kfe->e->v2, DEL);
2179 if (sf_vert_last->poly_nr < 2)
2180 BLI_remlink(&sf_ctx.fillvertbase, sf_vert_last);
2181 if (sf_vert->poly_nr < 2)
2182 BLI_remlink(&sf_ctx.fillvertbase, sf_vert);
2186 BLI_scanfill_calc(&sf_ctx, 0);
2188 for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next) {
2189 BMVert *v1 = sf_tri->v3->tmp.p, *v2 = sf_tri->v2->tmp.p, *v3 = sf_tri->v1->tmp.p;
2192 BMVert *verts[3] = {v1, v2, v3};
2194 if (v1 == v2 || v2 == v3 || v1 == v3)
2196 if (BM_face_exists(bm, verts, 3, &f2))
2199 f2 = BM_face_create_quad_tri(bm,
2203 BMO_elem_flag_enable(bm, f2, FACE_NEW);
2205 l_iter = BM_FACE_FIRST_LOOP(f2);
2207 BMO_elem_flag_disable(bm, l_iter->e, DEL);
2208 } while ((l_iter = l_iter->next) != BM_FACE_FIRST_LOOP(f2));
2210 BMO_elem_flag_disable(bm, f2, DEL);
2211 BM_elem_index_set(f2, i); /* set_dirty! *//* note, not 100% sure this is dirty? need to check */
2213 BM_face_normal_update(f2);
2214 if (dot_v3v3(f->no, f2->no) < 0.0f) {
2215 BM_face_normal_flip(bm, f2);
2219 BLI_scanfill_end(&sf_ctx);
2220 BLI_smallhash_release(hash);
2222 bm->elem_index_dirty |= BM_FACE;
2224 /* interpolate customdata */
2225 BM_ITER_MESH (f, &bmiter, bm, BM_FACES_OF_MESH) {
2230 if (!BMO_elem_flag_test(bm, f, FACE_NEW))
2233 f2 = faces[BM_elem_index_get(f)];
2234 if (BM_elem_index_get(f) < 0 || BM_elem_index_get(f) >= totface) {
2235 fprintf(stderr, "%s: face index out of range! (bmesh internal error)\n", __func__);
2238 BM_elem_attrs_copy(bm, bm, f2, f);
2240 BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
2241 BM_loop_interp_from_face(bm, l1, f2, true, true);
2245 /* merge triangles back into faces */
2248 /* delete left over faces */
2249 BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%ff context=%i", DEL, DEL_ONLYFACES);
2250 BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%fe context=%i", DEL, DEL_EDGES);
2251 BMO_op_callf(bm, BMO_FLAG_DEFAULTS, "delete geom=%fv context=%i", DEL, DEL_VERTS);
2254 MEM_freeN(face_nets);
2257 BLI_memarena_free(arena);
2260 BMO_error_clear(bm); /* remerge_faces sometimes raises errors, so make sure to clear them */
2262 bmesh_edit_end(bm, BMO_OPTYPE_FLAG_UNTAN_MULTIRES | BMO_OPTYPE_FLAG_NORMALS_CALC | BMO_OPTYPE_FLAG_SELECT_FLUSH);
2266 #else /* use direct (non-scanfill) method for cuts */
2268 /* sort list of kverts by fraction along edge e */
2269 static void sort_by_frac_along(ListBase *lst, BMEdge *e)
2271 /* note, since we know the point is along the edge, sort from distance to v1co */
2272 const float *v1co = e->v1->co;
2273 // const float *v2co = e->v2->co;
2274 Ref *cur = NULL, *prev = NULL, *next = NULL;
2276 if (lst->first == lst->last)
2279 for (cur = ((Ref *)lst->first)->next; cur; cur = next) {
2280 KnifeVert *vcur = cur->ref;
2282 const float vcur_fac = line_point_factor_v3(vcur->co, v1co, v2co);
2284 const float vcur_fac = len_squared_v3v3(v1co, vcur->co);
2290 BLI_remlink(lst, cur);
2293 KnifeVert *vprev = prev->ref;
2295 if (line_point_factor_v3(vprev->co, v1co, v2co) <= vcur_fac)
2298 if (len_squared_v3v3(v1co, vprev->co) <= vcur_fac)
2304 BLI_insertlinkafter(lst, prev, cur);
2308 /* The chain so far goes from an instantiated vertex to kfv (some may be reversed).
2309 * If possible, complete the chain to another instantiated vertex and return 1, else return 0.
2310 * The visited hash says which KnifeVert's have already been tried, not including kfv. */
2311 static bool find_chain_search(KnifeTool_OpData *kcd, KnifeVert *kfv, ListBase *fedges, SmallHash *visited,
2316 KnifeVert *kfv_other;
2321 BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2322 /* Try all possible next edges. Could either go through fedges
2323 * (all the KnifeEdges for the face being cut) or could go through
2324 * kve->edges and restrict to cutting face and uninstantiated edges.
2325 * Not clear which is better. Let's do the first. */
2326 for (r = fedges->first; r; r = r->next) {
2330 kfv_other = kfe->v2;
2331 else if (kfe->v2 == kfv)
2332 kfv_other = kfe->v1;
2333 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2334 knife_append_list(kcd, chain, kfe);
2335 if (find_chain_search(kcd, kfv_other, fedges, visited, chain))
2337 BLI_remlink(chain, chain->last);
2343 static ListBase *find_chain_from_vertex(KnifeTool_OpData *kcd, KnifeEdge *kfe, BMVert *v, ListBase *fedges)
2345 SmallHash visited_, *visited = &visited_;
2349 ans = knife_empty_list(kcd);
2350 knife_append_list(kcd, ans, kfe);
2352 BLI_smallhash_init(visited);
2353 if (kfe->v1->v == v) {
2354 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v1), NULL);
2355 found = find_chain_search(kcd, kfe->v2, fedges, visited, ans);
2358 BLI_assert(kfe->v2->v == v);
2359 BLI_smallhash_insert(visited, (uintptr_t)(kfe->v2), NULL);
2360 found = find_chain_search(kcd, kfe->v1, fedges, visited, ans);
2363 BLI_smallhash_release(visited);
2371 /* Find a chain in fedges from one instantiated vertex to another.
2372 * Remove the edges in the chain from fedges and return a separate list of the chain. */
2373 static ListBase *find_chain(KnifeTool_OpData *kcd, ListBase *fedges)
2382 for (r = fedges->first; r; r = r->next) {
2387 ans = knife_empty_list(kcd);
2388 knife_append_list(kcd, ans, kfe);
2392 ans = find_chain_from_vertex(kcd, kfe, v1, fedges);
2394 ans = find_chain_from_vertex(kcd, kfe, v2, fedges);
2399 BLI_assert(BLI_countlist(ans) > 0);
2400 for (r = ans->first; r; r = r->next) {
2401 ref = find_ref(fedges, r->ref);
2402 BLI_assert(ref != NULL);
2403 BLI_remlink(fedges, ref);
2409 /* The hole so far goes from kfvfirst to kfv (some may be reversed).
2410 * If possible, complete the hole back to kfvfirst and return 1, else return 0.
2411 * The visited hash says which KnifeVert's have already been tried, not including kfv or kfvfirst. */
2412 static bool find_hole_search(KnifeTool_OpData *kcd, KnifeVert *kfvfirst, KnifeVert *kfv, ListBase *fedges,
2413 SmallHash *visited, ListBase *hole)
2416 KnifeEdge *kfe, *kfelast;
2417 KnifeVert *kfv_other;
2419 if (kfv == kfvfirst)
2422 BLI_smallhash_insert(visited, (uintptr_t)kfv, NULL);
2423 kfelast = ((Ref *)hole->last)->ref;
2424 for (r = fedges->first; r; r = r->next) {
2428 if (kfe->v1->v || kfe->v2->v)
2432 kfv_other = kfe->v2;
2433 else if (kfe->v2 == kfv)
2434 kfv_other = kfe->v1;
2435 if (kfv_other && !BLI_smallhash_haskey(visited, (uintptr_t)kfv_other)) {
2436 knife_append_list(kcd, hole, kfe);
2437 if (find_hole_search(kcd, kfvfirst, kfv_other, fedges, visited, hole))
2439 BLI_remlink(hole, hole->last);
2445 /* Find a hole (simple cycle with no instantiated vertices).
2446 * Remove the edges in the cycle from fedges and return a separate list of the cycle */
2447 static ListBase *find_hole(KnifeTool_OpData *kcd, ListBase *fedges)
2452 SmallHash visited_, *visited = &visited_;
2458 for (r = fedges->first; r && !found; r = r->next) {
2460 if (kfe->v1->v || kfe->v2->v || kfe->v1 == kfe->v2)
2463 BLI_smallhash_init(visited);
2464 ans = knife_empty_list(kcd);
2465 knife_append_list(kcd, ans, kfe);
2467 found = find_hole_search(kcd, kfe->v1, kfe->v2, fedges, visited, ans);
2469 BLI_smallhash_release(visited);
2473 for (r = ans->first; r; r = r->next) {
2475 ref = find_ref(fedges, r->ref);
2477 BLI_remlink(fedges, ref);
2486 /* Try to find "nice" diagonals - short, and far apart from each other.
2487 * If found, return true and make a 'main chain' going across f which uses
2488 * the two diagonals and one part of the hole, and a 'side chain' that
2489 * completes the hole. */
2490 static bool find_hole_chains(KnifeTool_OpData *kcd, ListBase *hole, BMFace *f, ListBase **mainchain,
2491 ListBase **sidechain)
2498 KnifeVert *kfv, *kfvother;
2503 int nh, nf, i, j, k, m, ax, ay, sep = 0 /* Quite warnings */, bestsep;
2504 int besti[2], bestj[2];
2507 nh = BLI_countlist(hole);
2509 if (nh < 2 || nf < 3)
2512 /* Gather 2d projections of hole and face vertex coordinates.
2513 * Use best-axis projection - not completely accurate, maybe revisit */
2514 axis_dominant_v3(&ax, &ay, f->no);
2515 hco = BLI_memarena_alloc(kcd->arena, nh * sizeof(float *));
2516 fco = BLI_memarena_alloc(kcd->arena, nf * sizeof(float *));
2517 hv = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeVert *));
2518 fv = BLI_memarena_alloc(kcd->arena, nf * sizeof(BMVert *));
2519 he = BLI_memarena_alloc(kcd->arena, nh * sizeof(KnifeEdge *));
2524 for (r = hole->first; r; r = r->next) {
2527 if (kfvother == NULL) {
2532 BLI_assert(kfv == kfe->v1 || kfv == kfe->v2);
2534 hco[i] = BLI_memarena_alloc(kcd->arena, 2 * sizeof(float));
2535 hco[i][0] = kfv->co[ax];
2536 hco[i][1] = kfv->co[ay];
2538 kfvother = (kfe->v1 == kfv) ? kfe->v2 : kfe->v1;
2543 BM_ITER_ELEM (v, &iter, f, BM_VERTS_OF_FACE) {
2544 fco[j] = BLI_memarena_alloc(kcd->arena, 2 * sizeof(float));
2545 fco[j][0] = v->co[ax];
2546 fco[j][1] = v->co[ay];
2551 /* For first diagonal (m == 0), want shortest length.
2552 * For second diagonal (m == 1), want max separation of index of hole
2553 * vertex from the hole vertex used in the first diagonal, and from there
2554 * want the one with shortest length not to the same vertex as the first diagonal. */
2555 for (m = 0; m < 2; m++) {
2560 for (i = 0; i < nh; i++) {
2564 sep = (i + nh - besti[0]) % nh;
2565 sep = MIN2(sep, nh - sep);
2570 for (j = 0; j < nf; j++) {
2573 if (m == 1 && j == bestj[0])
2575 d = len_squared_v2v2(hco[i], fco[j]);
2580 for (k = 0; k < nh && ok; k++) {
2581 if (k == i || (k + 1) % nh == i)
2583 if (isect_line_line_v2(hco[i], fco[j], hco[k], hco[(k + 1) % nh]))
2588 for (k = 0; k < nf && ok; k++) {
2589 if (k == j || (k + 1) % nf == j)
2591 if (isect_line_line_v2(hco[i], fco[j], fco[k], fco[(k + 1) % nf]))
2605 if (besti[0] != -1 && besti[1] != -1) {
2606 BLI_assert(besti[0] != besti[1] && bestj[0] != bestj[1]);
2607 kfe = new_knife_edge(kcd);
2608 kfe->v1 = get_bm_knife_vert(kcd, fv[bestj[0]]);
2609 kfe->v2 = hv[besti[0]];
2610 chain = knife_empty_list(kcd);
2611 knife_append_list(kcd, chain, kfe);
2612 for (i = besti[0]; i != besti[1]; i = (i + 1) % nh) {
2613 knife_append_list(kcd, chain, he[i]);
2615 kfe = new_knife_edge(kcd);
2616 kfe->v1 = hv[besti[1]];
2617 kfe->v2 = get_bm_knife_vert(kcd, fv[bestj[1]]);
2618 knife_append_list(kcd, chain, kfe);
2621 chain = knife_empty_list(kcd);
2622 for (i = besti[1]; i != besti[0]; i = (i + 1) % nh) {
2623 knife_append_list(kcd, chain, he[i]);
2634 static bool knife_edge_in_face(KnifeTool_OpData *UNUSED(kcd), KnifeEdge *kfe, BMFace *f)
2636 /* BMesh *bm = kcd->em->bm; */ /* UNUSED */
2638 BMLoop *l1, *l2, *l;
2641 int v1inside, v2inside;
2651 /* find out if v1 and v2, if set, are part of the face */
2652 BM_ITER_ELEM (l, &iter, f, BM_LOOPS_OF_FACE) {
2653 if (v1 && l->v == v1)
2655 if (v2 && l->v == v2)
2659 /* BM_face_point_inside_test uses best-axis projection so this isn't most accurate test... */
2660 v1inside = l1 ? 0 : BM_face_point_inside_test(f, kfe->v1->co);
2661 v2inside = l2 ? 0 : BM_face_point_inside_test(f, kfe->v2->co);
2662 if ((l1 && v2inside) || (l2 && v1inside) || (v1inside && v2inside))
2665 /* Can have case where v1 and v2 are on shared chain between two faces.
2666 * BM_face_legal_splits does visibility and self-intersection tests,
2667 * but it is expensive and maybe a bit buggy, so use a simple
2668 * "is the midpoint in the face" test */
2669 mid_v3_v3v3(mid, kfe->v1->co, kfe->v2->co);
2670 return BM_face_point_inside_test(f, mid);
2675 /* Split face f with KnifeEdges on chain. f remains as one side, the face formed is put in *newface.
2676 * The new face will be on the left side of the chain as viewed from the normal-out side of f. */
2677 static void knife_make_chain_cut(KnifeTool_OpData *kcd, BMFace *f, ListBase *chain, BMFace **r_f_new)
2679 BMesh *bm = kcd->em->bm;
2680 KnifeEdge *kfe, *kfelast;
2684 KnifeVert *kfv, *kfvprev;
2685 BMLoop *l_new, *l_iter;
2687 int nco = BLI_countlist(chain) - 1;
2688 float (*cos)[3] = BLI_array_alloca(cos, nco);
2689 KnifeVert **kverts = BLI_array_alloca(kverts, nco);
2691 kfe = ((Ref *)chain->first)->ref;
2692 v1 = kfe->v1->v ? kfe->v1->v : kfe->v2->v;
2693 kfelast = ((Ref *)chain->last)->ref;
2694 v2 = kfelast->v2->v ? kfelast->v2->v : kfelast->v1->v;
2695 BLI_assert(v1 != NULL && v2 != NULL);
2696 kfvprev = kfe->v1->v == v1 ? kfe->v1 : kfe->v2;
2697 for (ref = chain->first, i = 0; i < nco && ref != chain->last; ref = ref->next, i++) {
2699 BLI_assert(kfvprev == kfe->v1 || kfvprev == kfe->v2);
2700 kfv = kfe->v1 == kfvprev ? kfe->v2 : kfe->v1;
2701 copy_v3_v3(cos[i], kfv->co);
2705 BLI_assert(i == nco);
2708 /* Want to prevent creating two-sided polygons */
2709 if (BM_edge_exists(v1, v2)) {
2713 f_new = BM_face_split(bm, f, v1, v2, &l_new, NULL, true);
2717 f_new = BM_face_split_n(bm, f, v1, v2, cos, nco, &l_new, NULL);
2719 /* Now go through lnew chain matching up chain kv's and assign real v's to them */
2720 for (l_iter = l_new->next, i = 0; i < nco; l_iter = l_iter->next, i++) {
2721 BLI_assert(equals_v3v3(cos[i], l_iter->v->co));
2722 if (kcd->select_result) {
2723 BM_edge_select_set(bm, l_iter->e, true);
2725 kverts[i]->v = l_iter->v;
2730 /* the select chain above doesnt account for the first loop */
2731 if (kcd->select_result) {
2733 BM_edge_select_set(bm, l_new->e, true);
2737 BM_elem_select_copy(bm, bm, f_new, f);
2743 static void knife_make_face_cuts(KnifeTool_OpData *kcd, BMFace *f, ListBase *kfedges)
2745 BMesh *bm = kcd->em->bm;
2747 BMFace *fnew, *fnew2, *fhole;
2748 ListBase *chain, *hole, *sidechain;
2749 ListBase *fnew_kfedges, *fnew2_kfedges;
2751 int count, oldcount;
2753 oldcount = BLI_countlist(kfedges);
2754 while ((chain = find_chain(kcd, kfedges)) != NULL) {
2755 knife_make_chain_cut(kcd, f, chain, &fnew);
2760 /* Move kfedges to fnew_kfedges if they are now in fnew.
2761 * The chain edges were removed already */
2762 fnew_kfedges = knife_empty_list(kcd);
2763 for (ref = kfedges->first; ref; ref = refnext) {
2765 refnext = ref->next;
2766 if (knife_edge_in_face(kcd, kfe, fnew)) {
2767 BLI_remlink(kfedges, ref);
2769 knife_append_list(kcd, fnew_kfedges, kfe);
2772 if (fnew_kfedges->first)
2773 knife_make_face_cuts(kcd, fnew, fnew_kfedges);
2775 /* find_chain should always remove edges if it returns true,
2776 * but guard against infinite loop anyway */
2777 count = BLI_countlist(kfedges);
2778 if (count >= oldcount) {
2779 BLI_assert(!"knife find_chain infinite loop");
2785 while ((hole = find_hole(kcd, kfedges)) != NULL) {
2786 if (find_hole_chains(kcd, hole, f, &chain, &sidechain)) {
2787 /* chain goes across f and sidechain comes back
2788 * from the second last vertex to the second vertex.
2790 knife_make_chain_cut(kcd, f, chain, &fnew);
2792 BLI_assert(!"knife failed hole cut");
2795 kfe = ((Ref *)sidechain->first)->ref;
2796 if (knife_edge_in_face(kcd, kfe, f)) {
2797 knife_make_chain_cut(kcd, f, sidechain, &fnew2);
2798 if (fnew2 == NULL) {
2803 else if (knife_edge_in_face(kcd, kfe, fnew)) {
2804 knife_make_chain_cut(kcd, fnew, sidechain, &fnew2);
2805 if (fnew2 == NULL) {
2811 /* shouldn't happen except in funny edge cases */
2814 BM_face_kill(bm, fhole);
2815 /* Move kfedges to either fnew or fnew2 if appropriate.
2816 * The hole edges were removed already */
2817 fnew_kfedges = knife_empty_list(kcd);
2818 fnew2_kfedges = knife_empty_list(kcd);
2819 for (ref = kfedges->first; ref; ref = refnext) {
2821 refnext = ref->next;
2822 if (knife_edge_in_face(kcd, kfe, fnew)) {
2823 BLI_remlink(kfedges, ref);
2825 knife_append_list(kcd, fnew_kfedges, kfe);
2827 else if (knife_edge_in_face(kcd, kfe, fnew2)) {
2828 BLI_remlink(kfedges, ref);
2830 knife_append_list(kcd, fnew2_kfedges, kfe);
2833 /* We'll skip knife edges that are in the newly formed hole.
2834 * (Maybe we shouldn't have made a hole in the first place?) */
2835 if (fnew != fhole && fnew_kfedges->first)
2836 knife_make_face_cuts(kcd, fnew, fnew_kfedges);
2837 if (fnew2 != fhole && fnew2_kfedges->first)
2838 knife_make_face_cuts(kcd, fnew2, fnew2_kfedges);
2841 /* find_hole should always remove edges if it returns true,
2842 * but guard against infinite loop anyway */
2843 count = BLI_countlist(kfedges);
2844 if (count >= oldcount) {
2845 BLI_assert(!"knife find_hole infinite loop");
2853 /* Use the network of KnifeEdges and KnifeVerts accumulated to make real BMVerts and BMEdedges */
2854 static void knife_make_cuts(KnifeTool_OpData *kcd)
2856 BMesh *bm = kcd->em->bm;
2864 SmallHashIter hiter;
2865 BLI_mempool_iter iter;
2866 SmallHash fhash_, *fhash = &fhash_;
2867 SmallHash ehash_, *ehash = &ehash_;
2869 BLI_smallhash_init(fhash);
2870 BLI_smallhash_init(ehash);
2872 /* put list of cutting edges for a face into fhash, keyed by face */
2873 BLI_mempool_iternew(kcd->kedges, &iter);
2874 for (kfe = BLI_mempool_iterstep(&iter); kfe; kfe = BLI_mempool_iterstep(&iter)) {
2878 lst = BLI_smallhash_lookup(fhash, (uintptr_t)f);
2880 lst = knife_empty_list(kcd);
2881 BLI_smallhash_insert(fhash, (uintptr_t)f, lst);
2883 knife_append_list(kcd, lst, kfe);
2886 /* put list of splitting vertices for an edge into ehash, keyed by edge */
2887 BLI_mempool_iternew(kcd->kverts, &iter);
2888 for (kfv = BLI_mempool_iterstep(&iter); kfv; kfv = BLI_mempool_iterstep(&iter)) {
2890 continue; /* already have a BMVert */
2891 for (ref = kfv->edges.first; ref; ref = ref->next) {
2896 lst = BLI_smallhash_lookup(ehash, (uintptr_t)e);
2898 lst = knife_empty_list(kcd);
2899 BLI_smallhash_insert(ehash, (uintptr_t)e, lst);
2901 /* there can be more than one kfe in kfv's list with same e */
2902 if (!find_ref(lst, kfv))
2903 knife_append_list(kcd, lst, kfv);
2907 /* split bmesh edges where needed */
2908 for (lst = BLI_smallhash_iternew(ehash, &hiter, (uintptr_t *)&e); lst;
2909 lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&e))
2911 sort_by_frac_along(lst, e);
2912 for (ref = lst->first; ref; ref = ref->next) {
2914 pct = line_point_factor_v3(kfv->co, e->v1->co, e->v2->co);
2915 kfv->v = BM_edge_split(bm, e, e->v1, &enew, pct);
2919 if (kcd->only_select) {
2920 EDBM_flag_disable_all(kcd->em, BM_ELEM_SELECT);
2923 /* do cuts for each face */
2924 for (lst = BLI_smallhash_iternew(fhash, &hiter, (uintptr_t *)&f); lst;
2925 lst = BLI_smallhash_iternext(&hiter, (uintptr_t *)&f))
2927 knife_make_face_cuts(kcd, f, lst);
2930 BLI_smallhash_release(fhash);
2931 BLI_smallhash_release(ehash);
2935 /* called on tool confirmation */
2936 static void knifetool_finish_ex(KnifeTool_OpData *kcd)
2939 knifenet_fill_faces(kcd);
2941 knife_make_cuts(kcd);
2944 EDBM_selectmode_flush(kcd->em);
2945 EDBM_mesh_normals_update(kcd->em);
2946 EDBM_update_generic(kcd->em, true, true);
2948 static void knifetool_finish(wmOperator *op)
2950 KnifeTool_OpData *kcd = op->customdata;
2951 knifetool_finish_ex(kcd);
2954 static void knife_recalc_projmat(KnifeTool_OpData *kcd)
2956 invert_m4_m4(kcd->ob->imat, kcd->ob->obmat);
2957 ED_view3d_ob_project_mat_get(kcd->ar->regiondata, kcd->ob, kcd->projmat);
2958 //mul_m4_m4m4(kcd->projmat, kcd->vc.rv3d->winmat, kcd->vc.rv3d->viewmat);
2960 kcd->is_ortho = ED_view3d_clip_range_get(kcd->vc.v3d, kcd->vc.rv3d,
2961 &kcd->clipsta, &kcd->clipend, true);
2964 /* called when modal loop selection is done... */
2965 static void knifetool_exit_ex(bContext *C, KnifeTool_OpData *kcd)
2970 if (kcd->is_interactive) {
2971 WM_cursor_modal_restore(CTX_wm_window(C));
2973 /* deactivate the extra drawing stuff in 3D-View */
2974 ED_region_draw_cb_exit(kcd->ar->type, kcd->draw_handle);
2977 /* free the custom data */
2978 BLI_mempool_destroy(kcd->refs);
2979 BLI_mempool_destroy(kcd->kverts);
2980 BLI_mempool_destroy(kcd->kedges);
2982 BLI_ghash_free(kcd->origedgemap, NULL, NULL);
2983 BLI_ghash_free(kcd->origvertmap, NULL, NULL);
2984 BLI_ghash_free(kcd->kedgefacemap, NULL, NULL);
2986 BKE_bmbvh_free(kcd->bmbvh);
2987 BLI_memarena_free(kcd->arena);
2989 /* tag for redraw */
2990 ED_region_tag_redraw(kcd->ar);
2993 MEM_freeN((void *)kcd->cagecos);
2996 MEM_freeN(kcd->linehits);
2998 /* destroy kcd itself */
3001 static void knifetool_exit(bContext *C, wmOperator *op)
3003 KnifeTool_OpData *kcd = op->customdata;
3004 knifetool_exit_ex(C, kcd);
3005 op->customdata = NULL;
3008 static void knifetool_update_mval(KnifeTool_OpData *kcd, const float mval[2])
3010 knife_recalc_projmat(kcd);
3011 copy_v2_v2(kcd->mval, mval);
3013 if (knife_update_active(kcd)) {
3014 ED_region_tag_redraw(kcd->ar);
3018 static void knifetool_update_mval_i(KnifeTool_OpData *kcd, const int mval_i[2])
3020 float mval[2] = {UNPACK2(mval_i)};
3021 knifetool_update_mval(kcd, mval);
3024 /* called when modal loop selection gets set up... */
3025 static void knifetool_init(bContext *C, KnifeTool_OpData *kcd,
3026 const bool only_select, const bool cut_through, const bool is_interactive)
3028 Scene *scene = CTX_data_scene(C);
3029 Object *obedit = CTX_data_edit_object(C);
3031 /* assign the drawing handle for drawing preview line... */
3033 kcd->ar = CTX_wm_region(C);
3035 em_setup_viewcontext(C, &kcd->vc);
3037 kcd->em = BKE_editmesh_from_object(kcd->ob);
3039 BM_mesh_elem_index_ensure(kcd->em->bm, BM_VERT);
3041 kcd->cagecos = (const float (*)[3])BKE_editmesh_vertexCos_get(kcd->em, scene, NULL);
3043 kcd->bmbvh = BKE_bmbvh_new(kcd->em,
3045 (only_select ? BMBVH_RESPECT_SELECT : BMBVH_RESPECT_HIDDEN),
3046 kcd->cagecos, false);
3048 kcd->arena = BLI_memarena_new(1 << 15, "knife");
3049 kcd->vthresh = KMAXDIST - 1;
3050 kcd->ethresh = KMAXDIST;
3054 knife_recalc_projmat(kcd);