Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / mesh / editmesh_utils.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * 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.
17  *
18  * The Original Code is Copyright (C) 2004 by Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joseph Eagar
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/editmesh_utils.c
29  *  \ingroup edmesh
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_mesh_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_key_types.h"
37
38 #include "BLI_math.h"
39 #include "BLI_alloca.h"
40 #include "BLI_buffer.h"
41 #include "BLI_kdtree.h"
42 #include "BLI_listbase.h"
43
44 #include "BKE_DerivedMesh.h"
45 #include "BKE_context.h"
46 #include "BKE_global.h"
47 #include "BKE_main.h"
48 #include "BKE_mesh.h"
49 #include "BKE_mesh_mapping.h"
50 #include "BKE_report.h"
51 #include "BKE_editmesh.h"
52 #include "BKE_editmesh_bvh.h"
53
54 #include "DEG_depsgraph.h"
55
56 #include "BKE_object.h"  /* XXX. only for EDBM_mesh_load(). */
57
58 #include "WM_api.h"
59 #include "WM_types.h"
60
61 #include "ED_mesh.h"
62 #include "ED_screen.h"
63 #include "ED_view3d.h"
64
65 #include "mesh_intern.h"  /* own include */
66
67 /* mesh backup implementation. This would greatly benefit from some sort of binary diffing
68  * just as the undo stack would. So leaving this as an interface for further work */
69
70 BMBackup EDBM_redo_state_store(BMEditMesh *em)
71 {
72         BMBackup backup;
73         backup.bmcopy = BM_mesh_copy(em->bm);
74         return backup;
75 }
76
77 void EDBM_redo_state_restore(BMBackup backup, BMEditMesh *em, int recalctess)
78 {
79         BMesh *tmpbm;
80         if (!em || !backup.bmcopy)
81                 return;
82
83         BM_mesh_data_free(em->bm);
84         tmpbm = BM_mesh_copy(backup.bmcopy);
85         *em->bm = *tmpbm;
86         MEM_freeN(tmpbm);
87         tmpbm = NULL;
88
89         if (recalctess)
90                 BKE_editmesh_tessface_calc(em);
91 }
92
93 void EDBM_redo_state_free(BMBackup *backup, BMEditMesh *em, int recalctess)
94 {
95         if (em && backup->bmcopy) {
96                 BM_mesh_data_free(em->bm);
97                 *em->bm = *backup->bmcopy;
98         }
99         else if (backup->bmcopy) {
100                 BM_mesh_data_free(backup->bmcopy);
101         }
102
103         if (backup->bmcopy)
104                 MEM_freeN(backup->bmcopy);
105         backup->bmcopy = NULL;
106
107         if (recalctess && em)
108                 BKE_editmesh_tessface_calc(em);
109 }
110
111 void EDBM_mesh_normals_update(BMEditMesh *em)
112 {
113         BM_mesh_normals_update(em->bm);
114 }
115
116 void EDBM_mesh_clear(BMEditMesh *em)
117 {
118         /* clear bmesh */
119         BM_mesh_clear(em->bm);
120         
121         /* free derived meshes */
122         BKE_editmesh_free_derivedmesh(em);
123         
124         /* free tessellation data */
125         em->tottri = 0;
126         if (em->looptris) {
127                 MEM_freeN(em->looptris);
128                 em->looptris = NULL;
129         }
130 }
131
132 void EDBM_stats_update(BMEditMesh *em)
133 {
134         const char iter_types[3] = {BM_VERTS_OF_MESH,
135                                     BM_EDGES_OF_MESH,
136                                     BM_FACES_OF_MESH};
137
138         BMIter iter;
139         BMElem *ele;
140         int *tots[3];
141         int i;
142
143         tots[0] = &em->bm->totvertsel;
144         tots[1] = &em->bm->totedgesel;
145         tots[2] = &em->bm->totfacesel;
146         
147         em->bm->totvertsel = em->bm->totedgesel = em->bm->totfacesel = 0;
148
149         for (i = 0; i < 3; i++) {
150                 ele = BM_iter_new(&iter, em->bm, iter_types[i], NULL);
151                 for ( ; ele; ele = BM_iter_step(&iter)) {
152                         if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
153                                 (*tots[i])++;
154                         }
155                 }
156         }
157 }
158
159 DerivedMesh *EDBM_mesh_deform_dm_get(BMEditMesh *em)
160 {
161         return ((em->derivedFinal != NULL) &&
162                 (em->derivedFinal->type == DM_TYPE_EDITBMESH) &&
163                 (em->derivedFinal->deformedOnly != false)) ? em->derivedFinal : NULL;
164 }
165
166 bool EDBM_op_init(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const char *fmt, ...)
167 {
168         BMesh *bm = em->bm;
169         va_list list;
170
171         va_start(list, fmt);
172
173         if (!BMO_op_vinitf(bm, bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
174                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
175                 va_end(list);
176                 return false;
177         }
178         
179         if (!em->emcopy)
180                 em->emcopy = BKE_editmesh_copy(em);
181         em->emcopyusers++;
182
183         va_end(list);
184
185         return true;
186 }
187
188
189 /* returns 0 on error, 1 on success.  executes and finishes a bmesh operator */
190 bool EDBM_op_finish(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const bool do_report)
191 {
192         const char *errmsg;
193         
194         BMO_op_finish(em->bm, bmop);
195
196         if (BMO_error_get(em->bm, &errmsg, NULL)) {
197                 BMEditMesh *emcopy = em->emcopy;
198
199                 if (do_report) {
200                         BKE_report(op->reports, RPT_ERROR, errmsg);
201                 }
202
203                 EDBM_mesh_free(em);
204                 *em = *emcopy;
205
206                 MEM_freeN(emcopy);
207                 em->emcopyusers = 0;
208                 em->emcopy = NULL;
209
210                 /* when copying, tessellation isn't to for faster copying,
211                  * but means we need to re-tessellate here */
212                 if (em->looptris == NULL) {
213                         BKE_editmesh_tessface_calc(em);
214                 }
215
216                 return false;
217         }
218         else {
219                 em->emcopyusers--;
220                 if (em->emcopyusers < 0) {
221                         printf("warning: em->emcopyusers was less than zero.\n");
222                 }
223
224                 if (em->emcopyusers <= 0) {
225                         BKE_editmesh_free(em->emcopy);
226                         MEM_freeN(em->emcopy);
227                         em->emcopy = NULL;
228                 }
229
230                 return true;
231         }
232 }
233
234 bool EDBM_op_callf(BMEditMesh *em, wmOperator *op, const char *fmt, ...)
235 {
236         BMesh *bm = em->bm;
237         BMOperator bmop;
238         va_list list;
239
240         va_start(list, fmt);
241
242         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
243                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
244                 va_end(list);
245                 return false;
246         }
247
248         if (!em->emcopy)
249                 em->emcopy = BKE_editmesh_copy(em);
250         em->emcopyusers++;
251
252         BMO_op_exec(bm, &bmop);
253
254         va_end(list);
255         return EDBM_op_finish(em, &bmop, op, true);
256 }
257
258 bool EDBM_op_call_and_selectf(BMEditMesh *em, wmOperator *op,
259                               const char *select_slot_out, const bool select_extend,
260                               const char *fmt, ...)
261 {
262         BMOpSlot *slot_select_out;
263         BMesh *bm = em->bm;
264         BMOperator bmop;
265         va_list list;
266         char hflag;
267
268         va_start(list, fmt);
269
270         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
271                 BKE_reportf(op->reports, RPT_ERROR, "Parse error in %s", __func__);
272                 va_end(list);
273                 return false;
274         }
275
276         if (!em->emcopy)
277                 em->emcopy = BKE_editmesh_copy(em);
278         em->emcopyusers++;
279
280         BMO_op_exec(bm, &bmop);
281
282         slot_select_out = BMO_slot_get(bmop.slots_out, select_slot_out);
283         hflag = slot_select_out->slot_subtype.elem & BM_ALL_NOLOOP;
284         BLI_assert(hflag != 0);
285
286         if (select_extend == false) {
287                 BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, BM_ELEM_SELECT, false);
288         }
289
290         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, select_slot_out, hflag, BM_ELEM_SELECT, true);
291
292         va_end(list);
293         return EDBM_op_finish(em, &bmop, op, true);
294 }
295
296 bool EDBM_op_call_silentf(BMEditMesh *em, const char *fmt, ...)
297 {
298         BMesh *bm = em->bm;
299         BMOperator bmop;
300         va_list list;
301
302         va_start(list, fmt);
303
304         if (!BMO_op_vinitf(bm, &bmop, BMO_FLAG_DEFAULTS, fmt, list)) {
305                 va_end(list);
306                 return false;
307         }
308
309         if (!em->emcopy)
310                 em->emcopy = BKE_editmesh_copy(em);
311         em->emcopyusers++;
312
313         BMO_op_exec(bm, &bmop);
314
315         va_end(list);
316         return EDBM_op_finish(em, &bmop, NULL, false);
317 }
318
319 void EDBM_selectmode_to_scene(bContext *C)
320 {
321         Scene *scene = CTX_data_scene(C);
322         Object *obedit = CTX_data_edit_object(C);
323         BMEditMesh *em = BKE_editmesh_from_object(obedit);
324
325         if (!em)
326                 return;
327
328         scene->toolsettings->selectmode = em->selectmode;
329
330         /* Request redraw of header buttons (to show new select mode) */
331         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, scene);
332 }
333
334 void EDBM_mesh_make(ToolSettings *ts, Object *ob, const bool add_key_index)
335 {
336         Mesh *me = ob->data;
337         BMesh *bm;
338
339         if (UNLIKELY(!me->mpoly && me->totface)) {
340                 BKE_mesh_convert_mfaces_to_mpolys(me);
341         }
342
343         bm = BKE_mesh_to_bmesh(
344                 me, ob, add_key_index,
345                 &((struct BMeshCreateParams){.use_toolflags = true,}));
346
347         if (me->edit_btmesh) {
348                 /* this happens when switching shape keys */
349                 EDBM_mesh_free(me->edit_btmesh);
350                 MEM_freeN(me->edit_btmesh);
351         }
352
353         /* currently executing operators re-tessellates, so we can avoid doing here
354          * but at some point it may need to be added back. */
355 #if 0
356         me->edit_btmesh = BKE_editmesh_create(bm, true);
357 #else
358         me->edit_btmesh = BKE_editmesh_create(bm, false);
359 #endif
360
361         me->edit_btmesh->selectmode = me->edit_btmesh->bm->selectmode = ts->selectmode;
362         me->edit_btmesh->mat_nr = (ob->actcol > 0) ? ob->actcol - 1 : 0;
363         me->edit_btmesh->ob = ob;
364
365         /* we need to flush selection because the mode may have changed from when last in editmode */
366         EDBM_selectmode_flush(me->edit_btmesh);
367 }
368
369 /**
370  * \warning This can invalidate the #DerivedMesh cache of other objects (for linked duplicates).
371  * Most callers should run #DEG_id_tag_update on \a ob->data, see: T46738, T46913
372  */
373 void EDBM_mesh_load(Object *ob)
374 {
375         Mesh *me = ob->data;
376         BMesh *bm = me->edit_btmesh->bm;
377
378         /* Workaround for T42360, 'ob->shapenr' should be 1 in this case.
379          * however this isn't synchronized between objects at the moment. */
380         if (UNLIKELY((ob->shapenr == 0) && (me->key && !BLI_listbase_is_empty(&me->key->block)))) {
381                 bm->shapenr = 1;
382         }
383
384         BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){0}));
385
386 #ifdef USE_TESSFACE_DEFAULT
387         BKE_mesh_tessface_calc(me);
388 #endif
389
390         /* Free derived mesh. usually this would happen through depsgraph but there
391          * are exceptions like file save that will not cause this, and we want to
392          * avoid ending up with an invalid derived mesh then.
393          *
394          * Do it for all objects which shares the same mesh datablock, since their
395          * derived meshes might also be referencing data which was just freed,
396          *
397          * Annoying enough, but currently seems most efficient way to avoid access
398          * of freed data on scene update, especially in cases when there are dependency
399          * cycles.
400          */
401         /*
402         for (Object *other_object = G.main->object.first;
403              other_object != NULL;
404              other_object = other_object->id.next)
405         {
406                 if (other_object->data == ob->data) {
407                         BKE_object_free_derived_caches(other_object);
408                 }
409         }
410         */
411 }
412
413 /**
414  * Should only be called on the active editmesh, otherwise call #BKE_editmesh_free
415  */
416 void EDBM_mesh_free(BMEditMesh *em)
417 {
418         /* These tables aren't used yet, so it's not strictly necessary
419          * to 'end' them (with 'e' param) but if someone tries to start
420          * using them, having these in place will save a lot of pain */
421         ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
422         ED_mesh_mirror_topo_table(NULL, NULL, 'e');
423
424         BKE_editmesh_free(em);
425 }
426
427 void EDBM_selectmode_flush_ex(BMEditMesh *em, const short selectmode)
428 {
429         BM_mesh_select_mode_flush_ex(em->bm, selectmode);
430 }
431
432 void EDBM_selectmode_flush(BMEditMesh *em)
433 {
434         EDBM_selectmode_flush_ex(em, em->selectmode);
435 }
436
437 void EDBM_deselect_flush(BMEditMesh *em)
438 {
439         /* function below doesnt use. just do this to keep the values in sync */
440         em->bm->selectmode = em->selectmode;
441         BM_mesh_deselect_flush(em->bm);
442 }
443
444
445 void EDBM_select_flush(BMEditMesh *em)
446 {
447         /* function below doesnt use. just do this to keep the values in sync */
448         em->bm->selectmode = em->selectmode;
449         BM_mesh_select_flush(em->bm);
450 }
451
452 void EDBM_select_more(BMEditMesh *em, const bool use_face_step)
453 {
454         BMOperator bmop;
455         const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
456
457         BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
458                      "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
459                      BM_ELEM_SELECT, false, use_faces, use_face_step);
460         BMO_op_exec(em->bm, &bmop);
461         /* don't flush selection in edge/vertex mode  */
462         BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
463         BMO_op_finish(em->bm, &bmop);
464
465         EDBM_selectmode_flush(em);
466 }
467
468 void EDBM_select_less(BMEditMesh *em, const bool use_face_step)
469 {
470         BMOperator bmop;
471         const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
472
473         BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
474                      "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
475                      BM_ELEM_SELECT, true, use_faces, use_face_step);
476         BMO_op_exec(em->bm, &bmop);
477         /* don't flush selection in edge/vertex mode  */
478         BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
479         BMO_op_finish(em->bm, &bmop);
480
481         EDBM_selectmode_flush(em);
482
483         /* only needed for select less, ensure we don't have isolated elements remaining */
484         BM_mesh_select_mode_clean(em->bm);
485 }
486
487 void EDBM_flag_disable_all(BMEditMesh *em, const char hflag)
488 {
489         BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, hflag, false);
490 }
491
492 void EDBM_flag_enable_all(BMEditMesh *em, const char hflag)
493 {
494         BM_mesh_elem_hflag_enable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, hflag, true);
495 }
496
497 /**
498  * Return a new UVVertMap from the editmesh
499  */
500 UvVertMap *BM_uv_vert_map_create(
501         BMesh *bm,
502         const float limit[2], const bool use_select, const bool use_winding)
503 {
504         BMVert *ev;
505         BMFace *efa;
506         BMLoop *l;
507         BMIter iter, liter;
508         /* vars from original func */
509         UvVertMap *vmap;
510         UvMapVert *buf;
511         MLoopUV *luv;
512         unsigned int a;
513         int totverts, i, totuv, totfaces;
514         const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
515         bool *winding = NULL;
516         BLI_buffer_declare_static(vec2f, tf_uv_buf, BLI_BUFFER_NOP, BM_DEFAULT_NGON_STACK_SIZE);
517
518         BM_mesh_elem_index_ensure(bm, BM_VERT | BM_FACE);
519         
520         totfaces = bm->totface;
521         totverts = bm->totvert;
522         totuv = 0;
523
524         /* generate UvMapVert array */
525         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
526                 if ((use_select == false) || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
527                         totuv += efa->len;
528                 }
529         }
530
531         if (totuv == 0) {
532                 return NULL;
533         }
534         vmap = (UvVertMap *)MEM_callocN(sizeof(*vmap), "UvVertMap");
535         if (!vmap) {
536                 return NULL;
537         }
538
539         vmap->vert = (UvMapVert **)MEM_callocN(sizeof(*vmap->vert) * totverts, "UvMapVert_pt");
540         buf = vmap->buf = (UvMapVert *)MEM_callocN(sizeof(*vmap->buf) * totuv, "UvMapVert");
541         if (use_winding) {
542                 winding = MEM_callocN(sizeof(*winding) * totfaces, "winding");
543         }
544
545         if (!vmap->vert || !vmap->buf) {
546                 BKE_mesh_uv_vert_map_free(vmap);
547                 return NULL;
548         }
549         
550         BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, a) {
551                 if ((use_select == false) || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
552                         float (*tf_uv)[2];
553
554                         if (use_winding) {
555                                 tf_uv = (float (*)[2])BLI_buffer_reinit_data(&tf_uv_buf, vec2f, efa->len);
556                         }
557
558                         BM_ITER_ELEM_INDEX(l, &liter, efa, BM_LOOPS_OF_FACE, i) {
559                                 buf->tfindex = i;
560                                 buf->f = a;
561                                 buf->separate = 0;
562                                 
563                                 buf->next = vmap->vert[BM_elem_index_get(l->v)];
564                                 vmap->vert[BM_elem_index_get(l->v)] = buf;
565                                 buf++;
566
567                                 if (use_winding) {
568                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
569                                         copy_v2_v2(tf_uv[i], luv->uv);
570                                 }
571                         }
572
573                         if (use_winding) {
574                                 winding[a] = cross_poly_v2(tf_uv, efa->len) > 0;
575                         }
576                 }
577         }
578         
579         /* sort individual uvs for each vert */
580         BM_ITER_MESH_INDEX (ev, &iter, bm, BM_VERTS_OF_MESH, a) {
581                 UvMapVert *newvlist = NULL, *vlist = vmap->vert[a];
582                 UvMapVert *iterv, *v, *lastv, *next;
583                 float *uv, *uv2, uvdiff[2];
584
585                 while (vlist) {
586                         v = vlist;
587                         vlist = vlist->next;
588                         v->next = newvlist;
589                         newvlist = v;
590
591                         efa = BM_face_at_index(bm, v->f);
592                         
593                         l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, v->tfindex);
594                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
595                         uv = luv->uv;
596                         
597                         lastv = NULL;
598                         iterv = vlist;
599
600                         while (iterv) {
601                                 next = iterv->next;
602                                 efa = BM_face_at_index(bm, iterv->f);
603                                 
604                                 l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, iterv->tfindex);
605                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
606                                 uv2 = luv->uv;
607                                 
608                                 sub_v2_v2v2(uvdiff, uv2, uv);
609
610                                 if (fabsf(uvdiff[0]) < limit[0] && fabsf(uvdiff[1]) < limit[1] &&
611                                     (!use_winding || winding[iterv->f] == winding[v->f]))
612                                 {
613                                         if (lastv) lastv->next = next;
614                                         else vlist = next;
615                                         iterv->next = newvlist;
616                                         newvlist = iterv;
617                                 }
618                                 else {
619                                         lastv = iterv;
620                                 }
621
622                                 iterv = next;
623                         }
624
625                         newvlist->separate = 1;
626                 }
627
628                 vmap->vert[a] = newvlist;
629         }
630
631         if (use_winding) {
632                 MEM_freeN(winding);
633         }
634
635         BLI_buffer_free(&tf_uv_buf);
636
637         return vmap;
638 }
639
640
641 UvMapVert *BM_uv_vert_map_at_index(UvVertMap *vmap, unsigned int v)
642 {
643         return vmap->vert[v];
644 }
645
646
647 /* A specialized vert map used by stitch operator */
648 UvElementMap *BM_uv_element_map_create(
649         BMesh *bm,
650         const bool selected, const bool use_winding, const bool do_islands)
651 {
652         BMVert *ev;
653         BMFace *efa;
654         BMLoop *l;
655         BMIter iter, liter;
656         /* vars from original func */
657         UvElementMap *element_map;
658         UvElement *buf;
659         bool *winding;
660         BLI_buffer_declare_static(vec2f, tf_uv_buf, BLI_BUFFER_NOP, BM_DEFAULT_NGON_STACK_SIZE);
661
662         MLoopUV *luv;
663         int totverts, totfaces, i, totuv, j;
664
665         const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
666
667         BM_mesh_elem_index_ensure(bm, BM_VERT | BM_FACE);
668
669         totfaces = bm->totface;
670         totverts = bm->totvert;
671         totuv = 0;
672
673         /* generate UvElement array */
674         BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
675                 if (!selected || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
676                         totuv += efa->len;
677                 }
678         }
679
680         if (totuv == 0) {
681                 return NULL;
682         }
683
684         element_map = (UvElementMap *)MEM_callocN(sizeof(*element_map), "UvElementMap");
685         element_map->totalUVs = totuv;
686         element_map->vert = (UvElement **)MEM_callocN(sizeof(*element_map->vert) * totverts, "UvElementVerts");
687         buf = element_map->buf = (UvElement *)MEM_callocN(sizeof(*element_map->buf) * totuv, "UvElement");
688
689         if (use_winding) {
690                 winding = MEM_mallocN(sizeof(*winding) * totfaces, "winding");
691         }
692
693         BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, j) {
694
695                 if (use_winding) {
696                         winding[j] = false;
697                 }
698
699                 if (!selected || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
700                         float (*tf_uv)[2];
701
702                         if (use_winding) {
703                                 tf_uv = (float (*)[2])BLI_buffer_reinit_data(&tf_uv_buf, vec2f, efa->len);
704                         }
705
706                         BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
707                                 buf->l = l;
708                                 buf->separate = 0;
709                                 buf->island = INVALID_ISLAND;
710                                 buf->tfindex = i;
711
712                                 buf->next = element_map->vert[BM_elem_index_get(l->v)];
713                                 element_map->vert[BM_elem_index_get(l->v)] = buf;
714
715                                 if (use_winding) {
716                                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
717                                         copy_v2_v2(tf_uv[i], luv->uv);
718                                 }
719
720                                 buf++;
721                         }
722
723                         if (use_winding) {
724                                 winding[j] = cross_poly_v2(tf_uv, efa->len) > 0;
725                         }
726                 }
727         }
728
729         /* sort individual uvs for each vert */
730         BM_ITER_MESH_INDEX (ev, &iter, bm, BM_VERTS_OF_MESH, i) {
731                 UvElement *newvlist = NULL, *vlist = element_map->vert[i];
732                 UvElement *iterv, *v, *lastv, *next;
733                 float *uv, *uv2, uvdiff[2];
734
735                 while (vlist) {
736                         v = vlist;
737                         vlist = vlist->next;
738                         v->next = newvlist;
739                         newvlist = v;
740
741                         l = v->l;
742                         luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
743                         uv = luv->uv;
744
745                         lastv = NULL;
746                         iterv = vlist;
747
748                         while (iterv) {
749                                 next = iterv->next;
750
751                                 l = iterv->l;
752                                 luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
753                                 uv2 = luv->uv;
754
755                                 sub_v2_v2v2(uvdiff, uv2, uv);
756
757                                 if (fabsf(uvdiff[0]) < STD_UV_CONNECT_LIMIT && fabsf(uvdiff[1]) < STD_UV_CONNECT_LIMIT &&
758                                     (!use_winding || winding[BM_elem_index_get(iterv->l->f)] == winding[BM_elem_index_get(v->l->f)]))
759                                 {
760                                         if (lastv) lastv->next = next;
761                                         else vlist = next;
762                                         iterv->next = newvlist;
763                                         newvlist = iterv;
764                                 }
765                                 else {
766                                         lastv = iterv;
767                                 }
768
769                                 iterv = next;
770                         }
771
772                         newvlist->separate = 1;
773                 }
774
775                 element_map->vert[i] = newvlist;
776         }
777
778         if (use_winding) {
779                 MEM_freeN(winding);
780         }
781
782         if (do_islands) {
783                 unsigned int *map;
784                 BMFace **stack;
785                 int stacksize = 0;
786                 UvElement *islandbuf;
787                 /* island number for faces */
788                 int *island_number = NULL;
789
790                 int nislands = 0, islandbufsize = 0;
791
792                 /* map holds the map from current vmap->buf to the new, sorted map */
793                 map = MEM_mallocN(sizeof(*map) * totuv, "uvelement_remap");
794                 stack = MEM_mallocN(sizeof(*stack) * bm->totface, "uv_island_face_stack");
795                 islandbuf = MEM_callocN(sizeof(*islandbuf) * totuv, "uvelement_island_buffer");
796                 island_number = MEM_mallocN(sizeof(*island_number) * totfaces, "uv_island_number_face");
797                 copy_vn_i(island_number, totfaces, INVALID_ISLAND);
798
799                 /* at this point, every UvElement in vert points to a UvElement sharing the same vertex. Now we should sort uv's in islands. */
800                 for (i = 0; i < totuv; i++) {
801                         if (element_map->buf[i].island == INVALID_ISLAND) {
802                                 element_map->buf[i].island = nislands;
803                                 stack[0] = element_map->buf[i].l->f;
804                                 island_number[BM_elem_index_get(stack[0])] = nislands;
805                                 stacksize = 1;
806
807                                 while (stacksize > 0) {
808                                         efa = stack[--stacksize];
809
810                                         BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
811                                                 UvElement *element, *initelement = element_map->vert[BM_elem_index_get(l->v)];
812
813                                                 for (element = initelement; element; element = element->next) {
814                                                         if (element->separate)
815                                                                 initelement = element;
816
817                                                         if (element->l->f == efa) {
818                                                                 /* found the uv corresponding to our face and vertex. Now fill it to the buffer */
819                                                                 element->island = nislands;
820                                                                 map[element - element_map->buf] = islandbufsize;
821                                                                 islandbuf[islandbufsize].l = element->l;
822                                                                 islandbuf[islandbufsize].separate = element->separate;
823                                                                 islandbuf[islandbufsize].tfindex = element->tfindex;
824                                                                 islandbuf[islandbufsize].island =  nislands;
825                                                                 islandbufsize++;
826
827                                                                 for (element = initelement; element; element = element->next) {
828                                                                         if (element->separate && element != initelement)
829                                                                                 break;
830
831                                                                         if (island_number[BM_elem_index_get(element->l->f)] == INVALID_ISLAND) {
832                                                                                 stack[stacksize++] = element->l->f;
833                                                                                 island_number[BM_elem_index_get(element->l->f)] = nislands;
834                                                                         }
835                                                                 }
836                                                                 break;
837                                                         }
838                                                 }
839                                         }
840                                 }
841
842                                 nislands++;
843                         }
844                 }
845
846                 MEM_freeN(island_number);
847
848                 /* remap */
849                 for (i = 0; i < bm->totvert; i++) {
850                         /* important since we may do selection only. Some of these may be NULL */
851                         if (element_map->vert[i])
852                                 element_map->vert[i] = &islandbuf[map[element_map->vert[i] - element_map->buf]];
853                 }
854
855                 element_map->islandIndices = MEM_callocN(sizeof(*element_map->islandIndices) * nislands, "UvElementMap_island_indices");
856                 j = 0;
857                 for (i = 0; i < totuv; i++) {
858                         UvElement *element = element_map->buf[i].next;
859                         if (element == NULL)
860                                 islandbuf[map[i]].next = NULL;
861                         else
862                                 islandbuf[map[i]].next = &islandbuf[map[element - element_map->buf]];
863
864                         if (islandbuf[i].island != j) {
865                                 j++;
866                                 element_map->islandIndices[j] = i;
867                         }
868                 }
869
870                 MEM_freeN(element_map->buf);
871
872                 element_map->buf = islandbuf;
873                 element_map->totalIslands = nislands;
874                 MEM_freeN(stack);
875                 MEM_freeN(map);
876         }
877
878         BLI_buffer_free(&tf_uv_buf);
879
880         return element_map;
881 }
882
883 void BM_uv_vert_map_free(UvVertMap *vmap)
884 {
885         if (vmap) {
886                 if (vmap->vert) MEM_freeN(vmap->vert);
887                 if (vmap->buf) MEM_freeN(vmap->buf);
888                 MEM_freeN(vmap);
889         }
890 }
891
892 void BM_uv_element_map_free(UvElementMap *element_map)
893 {
894         if (element_map) {
895                 if (element_map->vert) MEM_freeN(element_map->vert);
896                 if (element_map->buf) MEM_freeN(element_map->buf);
897                 if (element_map->islandIndices) MEM_freeN(element_map->islandIndices);
898                 MEM_freeN(element_map);
899         }
900 }
901
902 UvElement *BM_uv_element_get(UvElementMap *map, BMFace *efa, BMLoop *l)
903 {
904         UvElement *element;
905
906         element = map->vert[BM_elem_index_get(l->v)];
907
908         for (; element; element = element->next)
909                 if (element->l->f == efa)
910                         return element;
911
912         return NULL;
913 }
914
915 /* last_sel, use em->act_face otherwise get the last selected face in the editselections
916  * at the moment, last_sel is mainly useful for making sure the space image dosnt flicker */
917 BMFace *EDBM_uv_active_face_get(BMEditMesh *em, const bool sloppy, const bool selected)
918 {
919         BMFace *efa = NULL;
920         
921         if (!EDBM_uv_check(em))
922                 return NULL;
923         
924         efa = BM_mesh_active_face_get(em->bm, sloppy, selected);
925
926         if (efa) {
927                 return efa;
928         }
929
930         return NULL;
931 }
932
933 /* can we edit UV's for this mesh?*/
934 bool EDBM_uv_check(BMEditMesh *em)
935 {
936         /* some of these checks could be a touch overkill */
937         return em && em->bm->totface &&
938                CustomData_has_layer(&em->bm->ldata, CD_MLOOPUV);
939 }
940
941 bool EDBM_vert_color_check(BMEditMesh *em)
942 {
943         /* some of these checks could be a touch overkill */
944         return em && em->bm->totface && CustomData_has_layer(&em->bm->ldata, CD_MLOOPCOL);
945 }
946
947 static BMVert *cache_mirr_intptr_as_bmvert(intptr_t *index_lookup, int index)
948 {
949         intptr_t eve_i = index_lookup[index];
950         return (eve_i == -1) ? NULL : (BMVert *)eve_i;
951 }
952
953 /**
954  * Mirror editing API, usage:
955  *
956  * \code{.c}
957  * EDBM_verts_mirror_cache_begin(em, ...);
958  *
959  * BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
960  *     v_mirror = EDBM_verts_mirror_get(em, v);
961  *     e_mirror = EDBM_verts_mirror_get_edge(em, e);
962  *     f_mirror = EDBM_verts_mirror_get_face(em, f);
963  * }
964  *
965  * EDBM_verts_mirror_cache_end(em);
966  * \endcode
967  */
968
969 /* BM_SEARCH_MAXDIST is too big, copied from 2.6x MOC_THRESH, should become a
970  * preference */
971 #define BM_SEARCH_MAXDIST_MIRR 0.00002f
972 #define BM_CD_LAYER_ID "__mirror_index"
973 /**
974  * \param em  Editmesh.
975  * \param use_self  Allow a vertex to point to its self (middle verts).
976  * \param use_select  Restrict to selected verts.
977  * \param use_topology  Use topology mirror.
978  * \param maxdist  Distance for close point test.
979  * \param r_index  Optional array to write into, as an alternative to a customdata layer (length of total verts).
980  */
981 void EDBM_verts_mirror_cache_begin_ex(BMEditMesh *em, const int axis, const bool use_self, const bool use_select,
982                                       /* extra args */
983                                       const bool use_topology, float maxdist, int *r_index)
984 {
985         Mesh *me = (Mesh *)em->ob->data;
986         BMesh *bm = em->bm;
987         BMIter iter;
988         BMVert *v;
989         int cd_vmirr_offset;
990         int i;
991         const float maxdist_sq = SQUARE(maxdist);
992
993         /* one or the other is used depending if topo is enabled */
994         KDTree *tree = NULL;
995         MirrTopoStore_t mesh_topo_store = {NULL, -1, -1, -1};
996
997         BM_mesh_elem_table_ensure(bm, BM_VERT);
998
999         if (r_index == NULL) {
1000                 const char *layer_id = BM_CD_LAYER_ID;
1001                 em->mirror_cdlayer = CustomData_get_named_layer_index(&bm->vdata, CD_PROP_INT, layer_id);
1002                 if (em->mirror_cdlayer == -1) {
1003                         BM_data_layer_add_named(bm, &bm->vdata, CD_PROP_INT, layer_id);
1004                         em->mirror_cdlayer = CustomData_get_named_layer_index(&bm->vdata, CD_PROP_INT, layer_id);
1005                 }
1006
1007                 cd_vmirr_offset = CustomData_get_n_offset(&bm->vdata, CD_PROP_INT,
1008                                                           em->mirror_cdlayer - CustomData_get_layer_index(&bm->vdata, CD_PROP_INT));
1009
1010                 bm->vdata.layers[em->mirror_cdlayer].flag |= CD_FLAG_TEMPORARY;
1011         }
1012
1013         BM_mesh_elem_index_ensure(bm, BM_VERT);
1014
1015         if (use_topology) {
1016                 ED_mesh_mirrtopo_init(me, NULL, -1, &mesh_topo_store, true);
1017         }
1018         else {
1019                 tree = BLI_kdtree_new(bm->totvert);
1020                 BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
1021                         BLI_kdtree_insert(tree, i, v->co);
1022                 }
1023                 BLI_kdtree_balance(tree);
1024         }
1025
1026 #define VERT_INTPTR(_v, _i) r_index ? &r_index[_i] : BM_ELEM_CD_GET_VOID_P(_v, cd_vmirr_offset);
1027
1028         BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
1029                 BLI_assert(BM_elem_index_get(v) == i);
1030
1031                 /* temporary for testing, check for selection */
1032                 if (use_select && !BM_elem_flag_test(v, BM_ELEM_SELECT)) {
1033                         /* do nothing */
1034                 }
1035                 else {
1036                         BMVert *v_mirr;
1037                         int *idx = VERT_INTPTR(v, i);
1038
1039                         if (use_topology) {
1040                                 v_mirr = cache_mirr_intptr_as_bmvert(mesh_topo_store.index_lookup, i);
1041                         }
1042                         else {
1043                                 int i_mirr;
1044                                 float co[3];
1045                                 copy_v3_v3(co, v->co);
1046                                 co[axis] *= -1.0f;
1047
1048                                 v_mirr = NULL;
1049                                 i_mirr = BLI_kdtree_find_nearest(tree, co, NULL);
1050                                 if (i_mirr != -1) {
1051                                         BMVert *v_test = BM_vert_at_index(bm, i_mirr);
1052                                         if (len_squared_v3v3(co, v_test->co) < maxdist_sq) {
1053                                                 v_mirr = v_test;
1054                                         }
1055                                 }
1056                         }
1057
1058                         if (v_mirr && (use_self || (v_mirr != v))) {
1059                                 const int i_mirr = BM_elem_index_get(v_mirr);
1060                                 *idx = i_mirr;
1061                                 idx = VERT_INTPTR(v_mirr, i_mirr);
1062                                 *idx = i;
1063                         }
1064                         else {
1065                                 *idx = -1;
1066                         }
1067                 }
1068
1069         }
1070
1071 #undef VERT_INTPTR
1072
1073         if (use_topology) {
1074                 ED_mesh_mirrtopo_free(&mesh_topo_store);
1075         }
1076         else {
1077                 BLI_kdtree_free(tree);
1078         }
1079 }
1080
1081 void EDBM_verts_mirror_cache_begin(BMEditMesh *em, const int axis,
1082                                    const bool use_self, const bool use_select,
1083                                    const bool use_topology)
1084 {
1085         EDBM_verts_mirror_cache_begin_ex(em, axis,
1086                                          use_self, use_select,
1087                                          /* extra args */
1088                                          use_topology, BM_SEARCH_MAXDIST_MIRR, NULL);
1089 }
1090
1091 BMVert *EDBM_verts_mirror_get(BMEditMesh *em, BMVert *v)
1092 {
1093         const int *mirr = CustomData_bmesh_get_layer_n(&em->bm->vdata, v->head.data, em->mirror_cdlayer);
1094
1095         BLI_assert(em->mirror_cdlayer != -1); /* invalid use */
1096
1097         if (mirr && *mirr >= 0 && *mirr < em->bm->totvert) {
1098                 if (!em->bm->vtable) {
1099                         printf("err: should only be called between "
1100                                "EDBM_verts_mirror_cache_begin and EDBM_verts_mirror_cache_end");
1101                         return NULL;
1102                 }
1103
1104                 return em->bm->vtable[*mirr];
1105         }
1106
1107         return NULL;
1108 }
1109
1110 BMEdge *EDBM_verts_mirror_get_edge(BMEditMesh *em, BMEdge *e)
1111 {
1112         BMVert *v1_mirr = EDBM_verts_mirror_get(em, e->v1);
1113         if (v1_mirr) {
1114                 BMVert *v2_mirr = EDBM_verts_mirror_get(em, e->v2);
1115                 if (v2_mirr) {
1116                         return BM_edge_exists(v1_mirr, v2_mirr);
1117                 }
1118         }
1119
1120         return NULL;
1121 }
1122
1123 BMFace *EDBM_verts_mirror_get_face(BMEditMesh *em, BMFace *f)
1124 {
1125         BMVert **v_mirr_arr = BLI_array_alloca(v_mirr_arr, f->len);
1126
1127         BMLoop *l_iter, *l_first;
1128         unsigned int i = 0;
1129
1130         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
1131         do {
1132                 if ((v_mirr_arr[i++] = EDBM_verts_mirror_get(em, l_iter->v)) == NULL) {
1133                         return NULL;
1134                 }
1135         } while ((l_iter = l_iter->next) != l_first);
1136
1137         return BM_face_exists(v_mirr_arr, f->len);
1138 }
1139
1140 void EDBM_verts_mirror_cache_clear(BMEditMesh *em, BMVert *v)
1141 {
1142         int *mirr = CustomData_bmesh_get_layer_n(&em->bm->vdata, v->head.data, em->mirror_cdlayer);
1143
1144         BLI_assert(em->mirror_cdlayer != -1); /* invalid use */
1145
1146         if (mirr) {
1147                 *mirr = -1;
1148         }
1149 }
1150
1151 void EDBM_verts_mirror_cache_end(BMEditMesh *em)
1152 {
1153         em->mirror_cdlayer = -1;
1154 }
1155
1156 void EDBM_verts_mirror_apply(BMEditMesh *em, const int sel_from, const int sel_to)
1157 {
1158         BMIter iter;
1159         BMVert *v;
1160
1161         BLI_assert((em->bm->vtable != NULL) && ((em->bm->elem_table_dirty & BM_VERT) == 0));
1162
1163         BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
1164                 if (BM_elem_flag_test(v, BM_ELEM_SELECT) == sel_from) {
1165                         BMVert *mirr = EDBM_verts_mirror_get(em, v);
1166                         if (mirr) {
1167                                 if (BM_elem_flag_test(mirr, BM_ELEM_SELECT) == sel_to) {
1168                                         copy_v3_v3(mirr->co, v->co);
1169                                         mirr->co[0] *= -1.0f;
1170                                 }
1171                         }
1172                 }
1173         }
1174 }
1175
1176
1177 /* swap is 0 or 1, if 1 it hides not selected */
1178 void EDBM_mesh_hide(BMEditMesh *em, bool swap)
1179 {
1180         BMIter iter;
1181         BMElem *ele;
1182         int itermode;
1183         char hflag_swap = swap ? BM_ELEM_SELECT : 0;
1184
1185         if (em == NULL) return;
1186
1187         if (em->selectmode & SCE_SELECT_VERTEX)
1188                 itermode = BM_VERTS_OF_MESH;
1189         else if (em->selectmode & SCE_SELECT_EDGE)
1190                 itermode = BM_EDGES_OF_MESH;
1191         else
1192                 itermode = BM_FACES_OF_MESH;
1193
1194         BM_ITER_MESH (ele, &iter, em->bm, itermode) {
1195                 if (BM_elem_flag_test(ele, BM_ELEM_SELECT) ^ hflag_swap)
1196                         BM_elem_hide_set(em->bm, ele, true);
1197         }
1198
1199         EDBM_selectmode_flush(em);
1200
1201         /* original hide flushing comment (OUTDATED):
1202          * hide happens on least dominant select mode, and flushes up, not down! (helps preventing errors in subsurf) */
1203         /* - vertex hidden, always means edge is hidden too
1204          * - edge hidden, always means face is hidden too
1205          * - face hidden, only set face hide
1206          * - then only flush back down what's absolute hidden
1207          */
1208 }
1209
1210
1211 void EDBM_mesh_reveal(BMEditMesh *em, bool select)
1212 {
1213         const char iter_types[3] = {BM_VERTS_OF_MESH,
1214                                     BM_EDGES_OF_MESH,
1215                                     BM_FACES_OF_MESH};
1216
1217         const bool sels[3] = {
1218             (em->selectmode & SCE_SELECT_VERTEX) != 0,
1219             (em->selectmode & SCE_SELECT_EDGE) != 0,
1220             (em->selectmode & SCE_SELECT_FACE) != 0,
1221         };
1222         int i;
1223
1224         /* Use tag flag to remember what was hidden before all is revealed.
1225          * BM_ELEM_HIDDEN --> BM_ELEM_TAG */
1226         for (i = 0; i < 3; i++) {
1227                 BMIter iter;
1228                 BMElem *ele;
1229
1230                 BM_ITER_MESH (ele, &iter, em->bm, iter_types[i]) {
1231                         BM_elem_flag_set(ele, BM_ELEM_TAG, BM_elem_flag_test(ele, BM_ELEM_HIDDEN));
1232                 }
1233         }
1234
1235         /* Reveal everything */
1236         EDBM_flag_disable_all(em, BM_ELEM_HIDDEN);
1237
1238         /* Select relevant just-revealed elements */
1239         for (i = 0; i < 3; i++) {
1240                 BMIter iter;
1241                 BMElem *ele;
1242
1243                 if (!sels[i]) {
1244                         continue;
1245                 }
1246
1247                 BM_ITER_MESH (ele, &iter, em->bm, iter_types[i]) {
1248                         if (BM_elem_flag_test(ele, BM_ELEM_TAG)) {
1249                                 BM_elem_select_set(em->bm, ele, select);
1250                         }
1251                 }
1252         }
1253
1254         EDBM_selectmode_flush(em);
1255
1256         /* hidden faces can have invalid normals */
1257         EDBM_mesh_normals_update(em);
1258 }
1259
1260 /* so many tools call these that we better make it a generic function.
1261  */
1262 void EDBM_update_generic(BMEditMesh *em, const bool do_tessface, const bool is_destructive)
1263 {
1264         Object *ob = em->ob;
1265         /* order of calling isn't important */
1266         DEG_id_tag_update(ob->data, OB_RECALC_DATA);
1267         WM_main_add_notifier(NC_GEOM | ND_DATA, ob->data);
1268
1269         if (do_tessface) {
1270                 BKE_editmesh_tessface_calc(em);
1271         }
1272
1273         if (is_destructive) {
1274                 /* TODO. we may be able to remove this now! - Campbell */
1275                 // BM_mesh_elem_table_free(em->bm, BM_ALL_NOLOOP);
1276         }
1277         else {
1278                 /* in debug mode double check we didn't need to recalculate */
1279                 BLI_assert(BM_mesh_elem_table_check(em->bm) == true);
1280         }
1281
1282         /* don't keep stale derivedMesh data around, see: [#38872] */
1283         BKE_editmesh_free_derivedmesh(em);
1284
1285 #ifdef DEBUG
1286         {
1287                 BMEditSelection *ese;
1288                 for (ese = em->bm->selected.first; ese; ese = ese->next) {
1289                         BLI_assert(BM_elem_flag_test(ese->ele, BM_ELEM_SELECT));
1290                 }
1291         }
1292 #endif
1293 }
1294
1295 /* poll call for mesh operators requiring a view3d context */
1296 int EDBM_view3d_poll(bContext *C)
1297 {
1298         if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
1299                 return 1;
1300
1301         return 0;
1302 }
1303
1304 BMElem *EDBM_elem_from_selectmode(BMEditMesh *em, BMVert *eve, BMEdge *eed, BMFace *efa)
1305 {
1306         BMElem *ele = NULL;
1307
1308         if ((em->selectmode & SCE_SELECT_VERTEX) && eve) {
1309                 ele = (BMElem *)eve;
1310         }
1311         else if ((em->selectmode & SCE_SELECT_EDGE) && eed) {
1312                 ele = (BMElem *)eed;
1313         }
1314         else if ((em->selectmode & SCE_SELECT_FACE) && efa) {
1315                 ele = (BMElem *)efa;
1316         }
1317
1318         return ele;
1319 }
1320
1321 /**
1322  * Used when we want to store a single index for any vert/edge/face.
1323  *
1324  * Intended for use with operators.
1325  */
1326 int EDBM_elem_to_index_any(BMEditMesh *em, BMElem *ele)
1327 {
1328         BMesh *bm = em->bm;
1329         int index = BM_elem_index_get(ele);
1330
1331         if (ele->head.htype == BM_VERT) {
1332                 BLI_assert(!(bm->elem_index_dirty & BM_VERT));
1333         }
1334         else if (ele->head.htype == BM_EDGE) {
1335                 BLI_assert(!(bm->elem_index_dirty & BM_EDGE));
1336                 index += bm->totvert;
1337         }
1338         else if (ele->head.htype == BM_FACE) {
1339                 BLI_assert(!(bm->elem_index_dirty & BM_FACE));
1340                 index += bm->totvert + bm->totedge;
1341         }
1342         else {
1343                 BLI_assert(0);
1344         }
1345
1346         return index;
1347 }
1348
1349 BMElem *EDBM_elem_from_index_any(BMEditMesh *em, int index)
1350 {
1351         BMesh *bm = em->bm;
1352
1353         if (index < bm->totvert) {
1354                 return (BMElem *)BM_vert_at_index_find_or_table(bm, index);
1355         }
1356         index -= bm->totvert;
1357         if (index < bm->totedge) {
1358                 return (BMElem *)BM_edge_at_index_find_or_table(bm, index);
1359         }
1360         index -= bm->totedge;
1361         if (index < bm->totface) {
1362                 return (BMElem *)BM_face_at_index_find_or_table(bm, index);
1363         }
1364
1365         return NULL;
1366 }
1367
1368 /* -------------------------------------------------------------------- */
1369 /* BMBVH functions */
1370 // XXX
1371 #if 0 //BMESH_TODO: not implemented yet
1372 int BMBVH_VertVisible(BMBVHTree *tree, BMEdge *e, RegionView3D *r3d)
1373 {
1374
1375 }
1376 #endif
1377
1378 static BMFace *edge_ray_cast(struct BMBVHTree *tree, const float co[3], const float dir[3], float *r_hitout, BMEdge *e)
1379 {
1380         BMFace *f = BKE_bmbvh_ray_cast(tree, co, dir, 0.0f, NULL, r_hitout, NULL);
1381
1382         if (f && BM_edge_in_face(e, f))
1383                 return NULL;
1384
1385         return f;
1386 }
1387
1388 static void scale_point(float c1[3], const float p[3], const float s)
1389 {
1390         sub_v3_v3(c1, p);
1391         mul_v3_fl(c1, s);
1392         add_v3_v3(c1, p);
1393 }
1394
1395 bool BMBVH_EdgeVisible(struct BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v3d, Object *obedit)
1396 {
1397         BMFace *f;
1398         float co1[3], co2[3], co3[3], dir1[3], dir2[3], dir3[3];
1399         float origin[3], invmat[4][4];
1400         float epsilon = 0.01f;
1401         float end[3];
1402         const float mval_f[2] = {ar->winx / 2.0f,
1403                                  ar->winy / 2.0f};
1404
1405         ED_view3d_win_to_segment(ar, v3d, mval_f, origin, end, false);
1406
1407         invert_m4_m4(invmat, obedit->obmat);
1408         mul_m4_v3(invmat, origin);
1409
1410         copy_v3_v3(co1, e->v1->co);
1411         mid_v3_v3v3(co2, e->v1->co, e->v2->co);
1412         copy_v3_v3(co3, e->v2->co);
1413
1414         scale_point(co1, co2, 0.99);
1415         scale_point(co3, co2, 0.99);
1416
1417         /* ok, idea is to generate rays going from the camera origin to the
1418          * three points on the edge (v1, mid, v2)*/
1419         sub_v3_v3v3(dir1, origin, co1);
1420         sub_v3_v3v3(dir2, origin, co2);
1421         sub_v3_v3v3(dir3, origin, co3);
1422
1423         normalize_v3_length(dir1, epsilon);
1424         normalize_v3_length(dir2, epsilon);
1425         normalize_v3_length(dir3, epsilon);
1426
1427         /* offset coordinates slightly along view vectors, to avoid
1428          * hitting the faces that own the edge.*/
1429         add_v3_v3v3(co1, co1, dir1);
1430         add_v3_v3v3(co2, co2, dir2);
1431         add_v3_v3v3(co3, co3, dir3);
1432
1433         normalize_v3(dir1);
1434         normalize_v3(dir2);
1435         normalize_v3(dir3);
1436
1437         /* do three samplings: left, middle, right */
1438         f = edge_ray_cast(tree, co1, dir1, NULL, e);
1439         if (f && !edge_ray_cast(tree, co2, dir2, NULL, e))
1440                 return true;
1441         else if (f && !edge_ray_cast(tree, co3, dir3, NULL, e))
1442                 return true;
1443         else if (!f)
1444                 return true;
1445
1446         return false;
1447 }