8d6e7ae5b29d661ec56145ca411d271b0be5eeaf
[blender.git] / source / blender / bmesh / intern / bmesh_mesh.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  * Contributor(s): Geoffrey Bantle.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/intern/bmesh_mesh.c
24  *  \ingroup bmesh
25  *
26  * BM mesh level functions.
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_listBase.h"
32 #include "DNA_object_types.h"
33
34 #include "BLI_linklist_stack.h"
35 #include "BLI_listbase.h"
36 #include "BLI_math.h"
37 #include "BLI_stack.h"
38 #include "BLI_task.h"
39 #include "BLI_utildefines.h"
40
41 #include "BKE_cdderivedmesh.h"
42 #include "BKE_editmesh.h"
43 #include "BKE_mesh.h"
44 #include "BKE_multires.h"
45
46 #include "atomic_ops.h"
47
48 #include "intern/bmesh_private.h"
49
50 /* used as an extern, defined in bmesh.h */
51 const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
52 const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
53
54 static void bm_mempool_init_ex(
55         const BMAllocTemplate *allocsize, const bool use_toolflags,
56         BLI_mempool **r_vpool, BLI_mempool **r_epool, BLI_mempool **r_lpool, BLI_mempool **r_fpool)
57 {
58         size_t vert_size, edge_size, loop_size, face_size;
59
60         if (use_toolflags == true) {
61                 vert_size = sizeof(BMVert_OFlag);
62                 edge_size = sizeof(BMEdge_OFlag);
63                 loop_size = sizeof(BMLoop);
64                 face_size = sizeof(BMFace_OFlag);
65         }
66         else {
67                 vert_size = sizeof(BMVert);
68                 edge_size = sizeof(BMEdge);
69                 loop_size = sizeof(BMLoop);
70                 face_size = sizeof(BMFace);
71         }
72
73         if (r_vpool) {
74                 *r_vpool = BLI_mempool_create(
75                         vert_size, allocsize->totvert,
76                         bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
77         }
78         if (r_epool) {
79                 *r_epool = BLI_mempool_create(
80                         edge_size, allocsize->totedge,
81                         bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
82         }
83         if (r_lpool) {
84                 *r_lpool = BLI_mempool_create(
85                         loop_size, allocsize->totloop,
86                         bm_mesh_chunksize_default.totloop, BLI_MEMPOOL_NOP);
87         }
88         if (r_fpool) {
89                 *r_fpool = BLI_mempool_create(
90                         face_size, allocsize->totface,
91                         bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
92         }
93 }
94
95 static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize, const bool use_toolflags)
96 {
97         bm_mempool_init_ex(
98                 allocsize, use_toolflags,
99                 &bm->vpool, &bm->epool, &bm->lpool, &bm->fpool);
100
101 #ifdef USE_BMESH_HOLES
102         bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, BLI_MEMPOOL_NOP);
103 #endif
104 }
105
106 void BM_mesh_elem_toolflags_ensure(BMesh *bm)
107 {
108         BLI_assert(bm->use_toolflags);
109
110         if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
111                 return;
112         }
113
114         bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totvert, 512, BLI_MEMPOOL_NOP);
115         bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
116         bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
117
118         BMIter iter;
119         BMVert_OFlag *v_olfag;
120         BLI_mempool *toolflagpool = bm->vtoolflagpool;
121         BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
122                 v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
123         }
124
125         BMEdge_OFlag *e_olfag;
126         toolflagpool = bm->etoolflagpool;
127         BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
128                 e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
129         }
130
131         BMFace_OFlag *f_olfag;
132         toolflagpool = bm->ftoolflagpool;
133         BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
134                 f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
135         }
136
137         bm->totflags = 1;
138 }
139
140 void BM_mesh_elem_toolflags_clear(BMesh *bm)
141 {
142         if (bm->vtoolflagpool) {
143                 BLI_mempool_destroy(bm->vtoolflagpool);
144                 bm->vtoolflagpool = NULL;
145         }
146         if (bm->etoolflagpool) {
147                 BLI_mempool_destroy(bm->etoolflagpool);
148                 bm->etoolflagpool = NULL;
149         }
150         if (bm->ftoolflagpool) {
151                 BLI_mempool_destroy(bm->ftoolflagpool);
152                 bm->ftoolflagpool = NULL;
153         }
154 }
155
156 /**
157  * \brief BMesh Make Mesh
158  *
159  * Allocates a new BMesh structure.
160  *
161  * \return The New bmesh
162  *
163  * \note ob is needed by multires
164  */
165 BMesh *BM_mesh_create(
166         const BMAllocTemplate *allocsize,
167         const struct BMeshCreateParams *params)
168 {
169         /* allocate the structure */
170         BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
171         
172         /* allocate the memory pools for the mesh elements */
173         bm_mempool_init(bm, allocsize, params->use_toolflags);
174
175         /* allocate one flag pool that we don't get rid of. */
176         bm->use_toolflags = params->use_toolflags;
177         bm->toolflag_index = 0;
178         bm->totflags = 0;
179
180         CustomData_reset(&bm->vdata);
181         CustomData_reset(&bm->edata);
182         CustomData_reset(&bm->ldata);
183         CustomData_reset(&bm->pdata);
184
185         return bm;
186 }
187
188 /**
189  * \brief BMesh Free Mesh Data
190  *
191  *      Frees a BMesh structure.
192  *
193  * \note frees mesh, but not actual BMesh struct
194  */
195 void BM_mesh_data_free(BMesh *bm)
196 {
197         BMVert *v;
198         BMEdge *e;
199         BMLoop *l;
200         BMFace *f;
201
202         BMIter iter;
203         BMIter itersub;
204
205         const bool is_ldata_free = CustomData_bmesh_has_free(&bm->ldata);
206         const bool is_pdata_free = CustomData_bmesh_has_free(&bm->pdata);
207
208         /* Check if we have to call free, if not we can avoid a lot of looping */
209         if (CustomData_bmesh_has_free(&(bm->vdata))) {
210                 BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
211                         CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
212                 }
213         }
214         if (CustomData_bmesh_has_free(&(bm->edata))) {
215                 BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
216                         CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
217                 }
218         }
219
220         if (is_ldata_free || is_pdata_free) {
221                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
222                         if (is_pdata_free)
223                                 CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
224                         if (is_ldata_free) {
225                                 BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
226                                         CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
227                                 }
228                         }
229                 }
230         }
231
232         /* Free custom data pools, This should probably go in CustomData_free? */
233         if (bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
234         if (bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
235         if (bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
236         if (bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
237
238         /* free custom data */
239         CustomData_free(&bm->vdata, 0);
240         CustomData_free(&bm->edata, 0);
241         CustomData_free(&bm->ldata, 0);
242         CustomData_free(&bm->pdata, 0);
243
244         /* destroy element pools */
245         BLI_mempool_destroy(bm->vpool);
246         BLI_mempool_destroy(bm->epool);
247         BLI_mempool_destroy(bm->lpool);
248         BLI_mempool_destroy(bm->fpool);
249
250         if (bm->vtable) MEM_freeN(bm->vtable);
251         if (bm->etable) MEM_freeN(bm->etable);
252         if (bm->ftable) MEM_freeN(bm->ftable);
253
254         /* destroy flag pool */
255         BM_mesh_elem_toolflags_clear(bm);
256
257 #ifdef USE_BMESH_HOLES
258         BLI_mempool_destroy(bm->looplistpool);
259 #endif
260
261         BLI_freelistN(&bm->selected);
262
263         BMO_error_clear(bm);
264 }
265
266 /**
267  * \brief BMesh Clear Mesh
268  *
269  * Clear all data in bm
270  */
271 void BM_mesh_clear(BMesh *bm)
272 {
273         const bool use_toolflags = bm->use_toolflags;
274
275         /* free old mesh */
276         BM_mesh_data_free(bm);
277         memset(bm, 0, sizeof(BMesh));
278
279         /* allocate the memory pools for the mesh elements */
280         bm_mempool_init(bm, &bm_mesh_allocsize_default, use_toolflags);
281
282         bm->use_toolflags = use_toolflags;
283         bm->toolflag_index = 0;
284         bm->totflags = 0;
285
286         CustomData_reset(&bm->vdata);
287         CustomData_reset(&bm->edata);
288         CustomData_reset(&bm->ldata);
289         CustomData_reset(&bm->pdata);
290 }
291
292 /**
293  * \brief BMesh Free Mesh
294  *
295  *      Frees a BMesh data and its structure.
296  */
297 void BM_mesh_free(BMesh *bm)
298 {
299         BM_mesh_data_free(bm);
300
301         if (bm->py_handle) {
302                 /* keep this out of 'BM_mesh_data_free' because we want python
303                  * to be able to clear the mesh and maintain access. */
304                 bpy_bm_generic_invalidate(bm->py_handle);
305                 bm->py_handle = NULL;
306         }
307
308         MEM_freeN(bm);
309 }
310
311
312 /**
313  * Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
314  */
315
316 typedef struct BMEdgesCalcVectorsData {
317         /* Read-only data. */
318         const float (*vcos)[3];
319
320         /* Read-write data, but no need to protect it, no concurrency to fear here. */
321         float (*edgevec)[3];
322 } BMEdgesCalcVectorsData;
323
324
325 static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
326 {
327         BMEdgesCalcVectorsData *data = userdata;
328         BMEdge *e = (BMEdge *)mp_e;
329
330         if (e->l) {
331                 const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
332                 const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
333                 sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
334                 normalize_v3(data->edgevec[BM_elem_index_get(e)]);
335         }
336         else {
337                 /* the edge vector will not be needed when the edge has no radial */
338         }
339 }
340
341 static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
342 {
343         BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ?  BM_VERT : 0));
344
345         BMEdgesCalcVectorsData data = {
346             .vcos = vcos,
347             .edgevec = edgevec
348         };
349
350         BM_iter_parallel(bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
351 }
352
353
354 typedef struct BMVertsCalcNormalsData {
355         /* Read-only data. */
356         const float (*fnos)[3];
357         const float (*edgevec)[3];
358         const float (*vcos)[3];
359
360         /* Read-write data, protected by an atomic-based fake spinlock-like system... */
361         float (*vnos)[3];
362 } BMVertsCalcNormalsData;
363
364 static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
365 {
366         BMVertsCalcNormalsData *data = userdata;
367         BMFace *f = (BMFace *)mp_f;
368
369         const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
370
371         BMLoop *l_first, *l_iter;
372         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
373         do {
374                 const float *e1diff, *e2diff;
375                 float dotprod;
376                 float fac;
377
378                 /* calculate the dot product of the two edges that
379                  * meet at the loop's vertex */
380                 e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
381                 e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
382                 dotprod = dot_v3v3(e1diff, e2diff);
383
384                 /* edge vectors are calculated from e->v1 to e->v2, so
385                  * adjust the dot product if one but not both loops
386                  * actually runs from from e->v2 to e->v1 */
387                 if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
388                         dotprod = -dotprod;
389                 }
390
391                 fac = saacos(-dotprod);
392
393                 /* accumulate weighted face normal into the vertex's normal */
394                 float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
395
396                 /* This block is a lockless threadsafe madd_v3_v3fl.
397                  * It uses the first float of the vector as a sort of cheap spinlock,
398                  * assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
399                  * It also assumes that collisions between threads are highly unlikely,
400                  * else performances would be quite bad here. */
401                 float virtual_lock = v_no[0];
402                 while (true) {
403                         /* This loops until following conditions are met:
404                          *   - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
405                          *   - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
406                          */
407                         const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
408                         if (vl == virtual_lock && vl != FLT_MAX) {
409                                 break;
410                         }
411                         virtual_lock = vl;
412                 }
413                 BLI_assert(v_no[0] == FLT_MAX);
414                 /* Now we own that normal value, and can change it.
415                  * But first scalar of the vector must not be changed yet, it's our lock! */
416                 virtual_lock += f_no[0] * fac;
417                 v_no[1] += f_no[1] * fac;
418                 v_no[2] += f_no[2] * fac;
419                 /* Second atomic operation to 'release' our lock on that vector and set its first scalar value. */
420                 /* Note that we do not need to loop here, since we 'locked' v_no[0],
421                  * nobody should have changed it in the mean time. */
422                 virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
423                 BLI_assert(virtual_lock == FLT_MAX);
424
425         } while ((l_iter = l_iter->next) != l_first);
426 }
427
428 static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
429 {
430         BMVertsCalcNormalsData *data = userdata;
431         BMVert *v = (BMVert *)mp_v;
432
433         float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
434         if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
435                 const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
436                 normalize_v3_v3(v_no, v_co);
437         }
438 }
439
440 static void bm_mesh_verts_calc_normals(
441         BMesh *bm, const float (*edgevec)[3], const float (*fnos)[3],
442         const float (*vcos)[3], float (*vnos)[3])
443 {
444         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ?  BM_VERT : 0));
445
446         BMVertsCalcNormalsData data = {
447             .fnos = fnos,
448             .edgevec = edgevec,
449             .vcos = vcos,
450             .vnos = vnos
451         };
452
453         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
454
455         /* normalize the accumulated vertex normals */
456         BM_iter_parallel(bm, BM_VERTS_OF_MESH, mesh_verts_calc_normals_normalize_cb, &data, bm->totvert >= BM_OMP_LIMIT);
457 }
458
459
460 static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
461 {
462         BMFace *f = (BMFace *)mp_f;
463
464         BM_face_normal_update(f);
465 }
466
467
468 /**
469  * \brief BMesh Compute Normals
470  *
471  * Updates the normals of a mesh.
472  */
473 void BM_mesh_normals_update(BMesh *bm)
474 {
475         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
476
477         /* Parallel mempool iteration does not allow to generate indices inline anymore... */
478         BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
479
480         /* calculate all face normals */
481         BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
482
483         /* Zero out vertex normals */
484         BMIter viter;
485         BMVert *v;
486         int i;
487
488         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
489                 BM_elem_index_set(v, i); /* set_inline */
490                 zero_v3(v->no);
491         }
492         bm->elem_index_dirty &= ~BM_VERT;
493
494         /* Compute normalized direction vectors for each edge.
495          * Directions will be used for calculating the weights of the face normals on the vertex normals.
496          */
497         bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
498
499         /* Add weighted face normals to vertices, and normalize vert normals. */
500         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
501         MEM_freeN(edgevec);
502 }
503
504 /**
505  * \brief BMesh Compute Normals from/to external data.
506  *
507  * Computes the vertex normals of a mesh into vnos, using given vertex coordinates (vcos) and polygon normals (fnos).
508  */
509 void BM_verts_calc_normal_vcos(BMesh *bm, const float (*fnos)[3], const float (*vcos)[3], float (*vnos)[3])
510 {
511         float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
512
513         /* Compute normalized direction vectors for each edge.
514          * Directions will be used for calculating the weights of the face normals on the vertex normals.
515          */
516         bm_mesh_edges_calc_vectors(bm, edgevec, vcos);
517
518         /* Add weighted face normals to vertices, and normalize vert normals. */
519         bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, fnos, vcos, vnos);
520         MEM_freeN(edgevec);
521 }
522
523 /**
524  * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normals_vnos
525  */
526 static void bm_mesh_edges_sharp_tag(
527         BMesh *bm,
528         const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3],
529         const float split_angle, const bool do_sharp_edges_tag)
530 {
531         BMIter eiter;
532         BMEdge *e;
533         int i;
534
535         const bool check_angle = (split_angle < (float)M_PI);
536         const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
537
538         {
539                 char htype = BM_VERT | BM_LOOP;
540                 if (fnos) {
541                         htype |= BM_FACE;
542                 }
543                 BM_mesh_elem_index_ensure(bm, htype);
544         }
545
546         /* This first loop checks which edges are actually smooth, and pre-populate lnos with vnos (as if they were
547          * all smooth).
548          */
549         BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
550                 BMLoop *l_a, *l_b;
551
552                 BM_elem_index_set(e, i); /* set_inline */
553                 BM_elem_flag_disable(e, BM_ELEM_TAG); /* Clear tag (means edge is sharp). */
554
555                 /* An edge with only two loops, might be smooth... */
556                 if (BM_edge_loop_pair(e, &l_a, &l_b)) {
557                         bool is_angle_smooth = true;
558                         if (check_angle) {
559                                 const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
560                                 const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
561                                 is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
562                         }
563
564                         /* We only tag edges that are *really* smooth:
565                          * If the angle between both its polys' normals is below split_angle value,
566                          * and it is tagged as such,
567                          * and both its faces are smooth,
568                          * and both its faces have compatible (non-flipped) normals,
569                          * i.e. both loops on the same edge do not share the same vertex.
570                          */
571                         if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
572                             BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
573                             BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) &&
574                             l_a->v != l_b->v)
575                         {
576                                 if (is_angle_smooth) {
577                                         const float *no;
578                                         BM_elem_flag_enable(e, BM_ELEM_TAG);
579
580                                         /* linked vertices might be fully smooth, copy their normals to loop ones. */
581                                         if (r_lnos) {
582                                                 no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
583                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
584                                                 no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
585                                                 copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
586                                         }
587                                 }
588                                 else if (do_sharp_edges_tag) {
589                                         /* Note that we do not care about the other sharp-edge cases (sharp poly, non-manifold edge, etc.),
590                                          * only tag edge as sharp when it is due to angle threashold. */
591                                         BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
592                                 }
593                         }
594                 }
595         }
596
597         bm->elem_index_dirty &= ~BM_EDGE;
598 }
599
600 /* Check whether gievn loop is part of an unknown-so-far cyclic smooth fan, or not.
601  * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once. */
602 static bool bm_mesh_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
603 {
604         BMLoop *lfan_pivot_next = l_curr;
605         BMEdge *e_next = l_curr->e;
606
607         BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
608         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
609
610         while (true) {
611                 /* Much simpler than in sibling code with basic Mesh data! */
612                 lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
613
614                 if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
615                         /* Sharp loop/edge, so not a cyclic smooth fan... */
616                         return false;
617                 }
618                 /* Smooth loop/edge... */
619                 else if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
620                         if (lfan_pivot_next == l_curr) {
621                                 /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
622                                  * use initial l_curr/l_prev edge as start for this smooth fan. */
623                                 return true;
624                         }
625                         /* ... already checked in some previous looping, we can abort. */
626                         return false;
627                 }
628                 else {
629                         /* ... we can skip it in future, and keep checking the smooth fan. */
630                         BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
631                 }
632         }
633 }
634
635 /* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
636  * Will use first clnors_data array, and fallback to cd_loop_clnors_offset (use NULL and -1 to not use clnors). */
637 static void bm_mesh_loops_calc_normals(
638         BMesh *bm, const float (*vcos)[3], const float (*fnos)[3], float (*r_lnos)[3],
639         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
640 {
641         BMIter fiter;
642         BMFace *f_curr;
643         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
644
645         MLoopNorSpaceArray _lnors_spacearr = {NULL};
646
647         /* Temp normal stack. */
648         BLI_SMALLSTACK_DECLARE(normal, float *);
649         /* Temp clnors stack. */
650         BLI_SMALLSTACK_DECLARE(clnors, short *);
651         /* Temp edge vectors stack, only used when computing lnor spacearr. */
652         BLI_Stack *edge_vectors = NULL;
653
654         {
655                 char htype = 0;
656                 if (vcos) {
657                         htype |= BM_VERT;
658                 }
659                 /* Face/Loop indices are set inline below. */
660                 BM_mesh_elem_index_ensure(bm, htype);
661         }
662
663         if (!r_lnors_spacearr && has_clnors) {
664                 /* We need to compute lnor spacearr if some custom lnor data are given to us! */
665                 r_lnors_spacearr = &_lnors_spacearr;
666         }
667         if (r_lnors_spacearr) {
668                 BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop);
669                 edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
670         }
671
672         /* Clear all loops' tags (means none are to be skipped for now). */
673         int index_face, index_loop = 0;
674         BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
675                 BMLoop *l_curr, *l_first;
676
677                 BM_elem_index_set(f_curr, index_face); /* set_inline */
678
679                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
680                 do {
681                         BM_elem_index_set(l_curr, index_loop++); /* set_inline */
682                         BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
683                 } while ((l_curr = l_curr->next) != l_first);
684         }
685         bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
686
687         /* We now know edges that can be smoothed (they are tagged), and edges that will be hard (they aren't).
688          * Now, time to generate the normals.
689          */
690         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
691                 BMLoop *l_curr, *l_first;
692
693                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
694                 do {
695                         /* A smooth edge, we have to check for cyclic smooth fan case.
696                          * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
697                          * 'entry point', otherwise we can skip it. */
698                         /* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store mlfan_pivot's in a stack,
699                          * to avoid having to fan again around the vert during actual computation of clnor & clnorspace.
700                          * However, this would complicate the code, add more memory usage, and BM_vert_step_fan_loop()
701                          * is quite cheap in term of CPU cycles, so really think it's not worth it. */
702                         if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
703                             (BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !bm_mesh_loop_check_cyclic_smooth_fan(l_curr)))
704                         {
705                         }
706                         else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
707                                  !BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG))
708                         {
709                                 /* Simple case (both edges around that vertex are sharp in related polygon),
710                                  * this vertex just takes its poly normal.
711                                  */
712                                 const int l_curr_index = BM_elem_index_get(l_curr);
713                                 const float *no = fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no;
714                                 copy_v3_v3(r_lnos[l_curr_index], no);
715
716                                 /* If needed, generate this (simple!) lnor space. */
717                                 if (r_lnors_spacearr) {
718                                         float vec_curr[3], vec_prev[3];
719                                         MLoopNorSpace *lnor_space = BKE_lnor_space_create(r_lnors_spacearr);
720
721                                         {
722                                                 const BMVert *v_pivot = l_curr->v;
723                                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
724                                                 const BMVert *v_1 = BM_edge_other_vert(l_curr->e, v_pivot);
725                                                 const float *co_1 = vcos ? vcos[BM_elem_index_get(v_1)] : v_1->co;
726                                                 const BMVert *v_2 = BM_edge_other_vert(l_curr->prev->e, v_pivot);
727                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
728
729                                                 sub_v3_v3v3(vec_curr, co_1, co_pivot);
730                                                 normalize_v3(vec_curr);
731                                                 sub_v3_v3v3(vec_prev, co_2, co_pivot);
732                                                 normalize_v3(vec_prev);
733                                         }
734
735                                         BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
736                                         /* We know there is only one loop in this space, no need to create a linklist in this case... */
737                                         BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, false);
738
739                                         if (has_clnors) {
740                                                 short (*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
741                                                                                   BM_ELEM_CD_GET_VOID_P(l_curr, cd_loop_clnors_offset);
742                                                 BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor, r_lnos[l_curr_index]);
743                                         }
744                                 }
745                         }
746                         /* We *do not need* to check/tag loops as already computed!
747                          * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked more than
748                          * once!*
749                          * Since we consider edges having neighbor faces with inverted (flipped) normals as sharp, we are sure that
750                          * no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge), and not the
751                          * alternative (smooth curr_edge, sharp prev_edge).
752                          * All this due/thanks to link between normals and loop ordering.
753                          */
754                         else {
755                                 /* We have to fan around current vertex, until we find the other non-smooth edge,
756                                  * and accumulate face normals into the vertex!
757                                  * Note in case this vertex has only one sharp edge, this is a waste because the normal is the same as
758                                  * the vertex normal, but I do not see any easy way to detect that (would need to count number
759                                  * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as
760                                  * it should not be a common case in real-life meshes anyway).
761                                  */
762                                 BMVert *v_pivot = l_curr->v;
763                                 BMEdge *e_next;
764                                 const BMEdge *e_org = l_curr->e;
765                                 BMLoop *lfan_pivot, *lfan_pivot_next;
766                                 int lfan_pivot_index;
767                                 float lnor[3] = {0.0f, 0.0f, 0.0f};
768                                 float vec_curr[3], vec_next[3], vec_org[3];
769
770                                 /* We validate clnors data on the fly - cheapest way to do! */
771                                 int clnors_avg[2] = {0, 0};
772                                 short (*clnor_ref)[2] = NULL;
773                                 int clnors_nbr = 0;
774                                 bool clnors_invalid = false;
775
776                                 const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
777
778                                 MLoopNorSpace *lnor_space = r_lnors_spacearr ? BKE_lnor_space_create(r_lnors_spacearr) : NULL;
779
780                                 BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
781
782                                 lfan_pivot = l_curr;
783                                 lfan_pivot_index = BM_elem_index_get(lfan_pivot);
784                                 e_next = lfan_pivot->e;  /* Current edge here, actually! */
785
786                                 /* Only need to compute previous edge's vector once, then we can just reuse old current one! */
787                                 {
788                                         const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
789                                         const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
790
791                                         sub_v3_v3v3(vec_org, co_2, co_pivot);
792                                         normalize_v3(vec_org);
793                                         copy_v3_v3(vec_curr, vec_org);
794
795                                         if (r_lnors_spacearr) {
796                                                 BLI_stack_push(edge_vectors, vec_org);
797                                         }
798                                 }
799
800                                 while (true) {
801                                         /* Much simpler than in sibling code with basic Mesh data! */
802                                         lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot, &e_next);
803                                         if (lfan_pivot_next) {
804                                                 BLI_assert(lfan_pivot_next->v == v_pivot);
805                                         }
806                                         else {
807                                                 /* next edge is non-manifold, we have to find it ourselves! */
808                                                 e_next = (lfan_pivot->e == e_next) ? lfan_pivot->prev->e : lfan_pivot->e;
809                                         }
810
811                                         /* Compute edge vector.
812                                          * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them
813                                          *       twice (or more) here. However, time gained is not worth memory and time lost,
814                                          *       given the fact that this code should not be called that much in real-life meshes...
815                                          */
816                                         {
817                                                 const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
818                                                 const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
819
820                                                 sub_v3_v3v3(vec_next, co_2, co_pivot);
821                                                 normalize_v3(vec_next);
822                                         }
823
824                                         {
825                                                 /* Code similar to accumulate_vertex_normals_poly_v3. */
826                                                 /* Calculate angle between the two poly edges incident on this vertex. */
827                                                 const BMFace *f = lfan_pivot->f;
828                                                 const float fac = saacos(dot_v3v3(vec_next, vec_curr));
829                                                 const float *no = fnos ? fnos[BM_elem_index_get(f)] : f->no;
830                                                 /* Accumulate */
831                                                 madd_v3_v3fl(lnor, no, fac);
832
833                                                 if (has_clnors) {
834                                                         /* Accumulate all clnors, if they are not all equal we have to fix that! */
835                                                         short (*clnor)[2] = clnors_data ? &clnors_data[lfan_pivot_index] :
836                                                                                           BM_ELEM_CD_GET_VOID_P(lfan_pivot, cd_loop_clnors_offset);
837                                                         if (clnors_nbr) {
838                                                                 clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] || (*clnor_ref)[1] != (*clnor)[1]);
839                                                         }
840                                                         else {
841                                                                 clnor_ref = clnor;
842                                                         }
843                                                         clnors_avg[0] += (*clnor)[0];
844                                                         clnors_avg[1] += (*clnor)[1];
845                                                         clnors_nbr++;
846                                                         /* We store here a pointer to all custom lnors processed. */
847                                                         BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
848                                                 }
849                                         }
850
851                                         /* We store here a pointer to all loop-normals processed. */
852                                         BLI_SMALLSTACK_PUSH(normal, (float *)r_lnos[lfan_pivot_index]);
853
854                                         if (r_lnors_spacearr) {
855                                                 /* Assign current lnor space to current 'vertex' loop. */
856                                                 BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, true);
857                                                 if (e_next != e_org) {
858                                                         /* We store here all edges-normalized vectors processed. */
859                                                         BLI_stack_push(edge_vectors, vec_next);
860                                                 }
861                                         }
862
863                                         if (!BM_elem_flag_test(e_next, BM_ELEM_TAG) || (e_next == e_org)) {
864                                                 /* Next edge is sharp, we have finished with this fan of faces around this vert! */
865                                                 break;
866                                         }
867
868                                         /* Copy next edge vector to current one. */
869                                         copy_v3_v3(vec_curr, vec_next);
870                                         /* Next pivot loop to current one. */
871                                         lfan_pivot = lfan_pivot_next;
872                                         lfan_pivot_index = BM_elem_index_get(lfan_pivot);
873                                 }
874
875                                 {
876                                         float lnor_len = normalize_v3(lnor);
877
878                                         /* If we are generating lnor spacearr, we can now define the one for this fan. */
879                                         if (r_lnors_spacearr) {
880                                                 if (UNLIKELY(lnor_len == 0.0f)) {
881                                                         /* Use vertex normal as fallback! */
882                                                         copy_v3_v3(lnor, r_lnos[lfan_pivot_index]);
883                                                         lnor_len = 1.0f;
884                                                 }
885
886                                                 BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_next, edge_vectors);
887
888                                                 if (has_clnors) {
889                                                         if (clnors_invalid) {
890                                                                 short *clnor;
891
892                                                                 clnors_avg[0] /= clnors_nbr;
893                                                                 clnors_avg[1] /= clnors_nbr;
894                                                                 /* Fix/update all clnors of this fan with computed average value. */
895                                                                 printf("Invalid clnors in this fan!\n");
896                                                                 while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
897                                                                         //print_v2("org clnor", clnor);
898                                                                         clnor[0] = (short)clnors_avg[0];
899                                                                         clnor[1] = (short)clnors_avg[1];
900                                                                 }
901                                                                 //print_v2("new clnors", clnors_avg);
902                                                         }
903                                                         else {
904                                                                 /* We still have to consume the stack! */
905                                                                 while (BLI_SMALLSTACK_POP(clnors));
906                                                         }
907                                                         BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
908                                                 }
909                                         }
910
911                                         /* In case we get a zero normal here, just use vertex normal already set! */
912                                         if (LIKELY(lnor_len != 0.0f)) {
913                                                 /* Copy back the final computed normal into all related loop-normals. */
914                                                 float *nor;
915
916                                                 while ((nor = BLI_SMALLSTACK_POP(normal))) {
917                                                         copy_v3_v3(nor, lnor);
918                                                 }
919                                         }
920                                         else {
921                                                 /* We still have to consume the stack! */
922                                                 while (BLI_SMALLSTACK_POP(normal));
923                                         }
924                                 }
925
926                                 /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one). */
927                                 if (r_lnors_spacearr) {
928                                         BM_elem_flag_enable(l_curr->v, BM_ELEM_TAG);
929                                 }
930                         }
931                 } while ((l_curr = l_curr->next) != l_first);
932         }
933
934         if (r_lnors_spacearr) {
935                 BLI_stack_free(edge_vectors);
936                 if (r_lnors_spacearr == &_lnors_spacearr) {
937                         BKE_lnor_spacearr_free(r_lnors_spacearr);
938                 }
939         }
940 }
941
942 static void bm_mesh_loops_calc_normals_no_autosmooth(
943         BMesh *bm, const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3])
944 {
945         BMIter fiter;
946         BMFace *f_curr;
947
948         {
949                 char htype = BM_LOOP;
950                 if (vnos) {
951                         htype |= BM_VERT;
952                 }
953                 if (fnos) {
954                         htype |= BM_FACE;
955                 }
956                 BM_mesh_elem_index_ensure(bm, htype);
957         }
958
959         BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
960                 BMLoop *l_curr, *l_first;
961                 const bool is_face_flat = !BM_elem_flag_test(f_curr, BM_ELEM_SMOOTH);
962
963                 l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
964                 do {
965                         const float *no = is_face_flat ? (fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no) :
966                                                          (vnos ? vnos[BM_elem_index_get(l_curr->v)] : l_curr->v->no);
967                         copy_v3_v3(r_lnos[BM_elem_index_get(l_curr)], no);
968
969                 } while ((l_curr = l_curr->next) != l_first);
970         }
971 }
972
973 #if 0  /* Unused currently */
974 /**
975  * \brief BMesh Compute Loop Normals
976  *
977  * Updates the loop normals of a mesh. Assumes vertex and face normals are valid (else call BM_mesh_normals_update()
978  * first)!
979  */
980 void BM_mesh_loop_normals_update(
981         BMesh *bm, const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
982         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
983 {
984         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
985
986         if (use_split_normals) {
987                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
988                  * When using custom loop normals, disable the angle feature! */
989                 bm_mesh_edges_sharp_tag(bm, NULL, NULL, has_clnors ? (float)M_PI : split_angle, r_lnos);
990
991                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
992                 bm_mesh_loops_calc_normals(bm, NULL, NULL, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
993         }
994         else {
995                 BLI_assert(!r_lnors_spacearr);
996                 bm_mesh_loops_calc_normals_no_autosmooth(bm, NULL, NULL, r_lnos);
997         }
998 }
999 #endif
1000
1001 /**
1002  * \brief BMesh Compute Loop Normals from/to external data.
1003  *
1004  * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
1005  * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
1006  */
1007 void BM_loops_calc_normal_vcos(
1008         BMesh *bm, const float (*vcos)[3], const float (*vnos)[3], const float (*fnos)[3],
1009         const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
1010         MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset)
1011 {
1012         const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
1013
1014         if (use_split_normals) {
1015                 /* Tag smooth edges and set lnos from vnos when they might be completely smooth...
1016                  * When using custom loop normals, disable the angle feature! */
1017                 bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
1018
1019                 /* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
1020                 bm_mesh_loops_calc_normals(bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
1021         }
1022         else {
1023                 BLI_assert(!r_lnors_spacearr);
1024                 bm_mesh_loops_calc_normals_no_autosmooth(bm, vnos, fnos, r_lnos);
1025         }
1026 }
1027
1028 /** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
1029  *
1030  * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
1031  */
1032 void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
1033 {
1034         if (split_angle >= (float)M_PI) {
1035                 /* Nothing to do! */
1036                 return;
1037         }
1038
1039         bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
1040 }
1041
1042 static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from, int to)
1043 {
1044         /* switch multires data out of tangent space */
1045         if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1046                 BMEditMesh *em = BKE_editmesh_create(bm, false);
1047                 DerivedMesh *dm = CDDM_from_editbmesh(em, true, false);
1048                 MDisps *mdisps;
1049                 BMFace *f;
1050                 BMIter iter;
1051                 // int i = 0; // UNUSED
1052                 
1053                 multires_set_space(dm, ob, from, to);
1054                 
1055                 mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS);
1056                 
1057                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
1058                         BMLoop *l;
1059                         BMIter liter;
1060                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
1061                                 MDisps *lmd = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_MDISPS);
1062                                 
1063                                 if (!lmd->disps) {
1064                                         printf("%s: warning - 'lmd->disps' == NULL\n", __func__);
1065                                 }
1066                                 
1067                                 if (lmd->disps && lmd->totdisp == mdisps->totdisp) {
1068                                         memcpy(lmd->disps, mdisps->disps, sizeof(float) * 3 * lmd->totdisp);
1069                                 }
1070                                 else if (mdisps->disps) {
1071                                         if (lmd->disps)
1072                                                 MEM_freeN(lmd->disps);
1073                                         
1074                                         lmd->disps = MEM_dupallocN(mdisps->disps);
1075                                         lmd->totdisp = mdisps->totdisp;
1076                                         lmd->level = mdisps->level;
1077                                 }
1078                                 
1079                                 mdisps++;
1080                                 // i += 1;
1081                         }
1082                 }
1083                 
1084                 dm->needsFree = 1;
1085                 dm->release(dm);
1086                 
1087                 /* setting this to NULL prevents BKE_editmesh_free from freeing it */
1088                 em->bm = NULL;
1089                 BKE_editmesh_free(em);
1090                 MEM_freeN(em);
1091         }
1092 }
1093
1094 /**
1095  * \brief BMesh Begin Edit
1096  *
1097  * Functions for setting up a mesh for editing and cleaning up after
1098  * the editing operations are done. These are called by the tools/operator
1099  * API for each time a tool is executed.
1100  */
1101 void bmesh_edit_begin(BMesh *UNUSED(bm), BMOpTypeFlag UNUSED(type_flag))
1102 {
1103         /* Most operators seem to be using BMO_OPTYPE_FLAG_UNTAN_MULTIRES to change the MDisps to
1104          * absolute space during mesh edits. With this enabled, changes to the topology
1105          * (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
1106          * the mesh at all, which doesn't seem right. Turning off completely for now,
1107          * until this is shown to be better for certain types of mesh edits. */
1108 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1109         /* switch multires data out of tangent space */
1110         if ((type_flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1111                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
1112
1113                 /* ensure correct normals, if possible */
1114                 bmesh_rationalize_normals(bm, 0);
1115                 BM_mesh_normals_update(bm);
1116         }
1117 #endif
1118 }
1119
1120 /**
1121  * \brief BMesh End Edit
1122  */
1123 void bmesh_edit_end(BMesh *bm, BMOpTypeFlag type_flag)
1124 {
1125         ListBase select_history;
1126
1127         /* BMO_OPTYPE_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
1128 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
1129         /* switch multires data into tangent space */
1130         if ((flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
1131                 /* set normals to their previous winding */
1132                 bmesh_rationalize_normals(bm, 1);
1133                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
1134         }
1135         else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
1136                 bmesh_rationalize_normals(bm, 1);
1137         }
1138 #endif
1139
1140         /* compute normals, clear temp flags and flush selections */
1141         if (type_flag & BMO_OPTYPE_FLAG_NORMALS_CALC) {
1142                 BM_mesh_normals_update(bm);
1143         }
1144
1145
1146         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1147                 select_history = bm->selected;
1148                 BLI_listbase_clear(&bm->selected);
1149         }
1150
1151         if (type_flag & BMO_OPTYPE_FLAG_SELECT_FLUSH) {
1152                 BM_mesh_select_mode_flush(bm);
1153         }
1154
1155         if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
1156                 bm->selected = select_history;
1157         }
1158 }
1159
1160 void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
1161 {
1162         const char htype_needed = bm->elem_index_dirty & htype;
1163
1164 #ifdef DEBUG
1165         BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
1166 #endif
1167
1168         if (0 && htype_needed == 0) {
1169                 goto finally;
1170         }
1171
1172         if (htype & BM_VERT) {
1173                 if (bm->elem_index_dirty & BM_VERT) {
1174                         BMIter iter;
1175                         BMElem *ele;
1176
1177                         int index;
1178                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
1179                                 BM_elem_index_set(ele, index); /* set_ok */
1180                         }
1181                         BLI_assert(index == bm->totvert);
1182                 }
1183                 else {
1184                         // printf("%s: skipping vert index calc!\n", __func__);
1185                 }
1186         }
1187
1188         if (htype & BM_EDGE) {
1189                 if (bm->elem_index_dirty & BM_EDGE) {
1190                         BMIter iter;
1191                         BMElem *ele;
1192
1193                         int index;
1194                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
1195                                 BM_elem_index_set(ele, index); /* set_ok */
1196                         }
1197                         BLI_assert(index == bm->totedge);
1198                 }
1199                 else {
1200                         // printf("%s: skipping edge index calc!\n", __func__);
1201                 }
1202         }
1203
1204         if (htype & (BM_FACE | BM_LOOP)) {
1205                 if (bm->elem_index_dirty & (BM_FACE | BM_LOOP)) {
1206                         BMIter iter;
1207                         BMElem *ele;
1208
1209                         const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
1210                         const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
1211
1212                         int index;
1213                         int index_loop = 0;
1214
1215                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
1216                                 if (update_face) {
1217                                         BM_elem_index_set(ele, index); /* set_ok */
1218                                 }
1219
1220                                 if (update_loop) {
1221                                         BMLoop *l_iter, *l_first;
1222
1223                                         l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
1224                                         do {
1225                                                 BM_elem_index_set(l_iter, index_loop++); /* set_ok */
1226                                         } while ((l_iter = l_iter->next) != l_first);
1227                                 }
1228                         }
1229
1230                         BLI_assert(index == bm->totface);
1231                         if (update_loop) {
1232                                 BLI_assert(index_loop == bm->totloop);
1233                         }
1234                 }
1235                 else {
1236                         // printf("%s: skipping face/loop index calc!\n", __func__);
1237                 }
1238         }
1239
1240 finally:
1241         bm->elem_index_dirty &= ~htype;
1242 }
1243
1244
1245 /**
1246  * Array checking/setting macros
1247  *
1248  * Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
1249  *
1250  * To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
1251  * this flag is set incorrectly which could crash blender.
1252  *
1253  * These functions ensure its correct and are called more often in debug mode.
1254  */
1255
1256 void BM_mesh_elem_index_validate(
1257         BMesh *bm, const char *location, const char *func,
1258         const char *msg_a, const char *msg_b)
1259 {
1260         const char iter_types[3] = {BM_VERTS_OF_MESH,
1261                                     BM_EDGES_OF_MESH,
1262                                     BM_FACES_OF_MESH};
1263
1264         const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
1265         const char *type_names[3] = {"vert", "edge", "face"};
1266
1267         BMIter iter;
1268         BMElem *ele;
1269         int i;
1270         bool is_any_error = 0;
1271
1272         for (i = 0; i < 3; i++) {
1273                 const bool is_dirty = (flag_types[i] & bm->elem_index_dirty) != 0;
1274                 int index = 0;
1275                 bool is_error = false;
1276                 int err_val = 0;
1277                 int err_idx = 0;
1278
1279                 BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
1280                         if (!is_dirty) {
1281                                 if (BM_elem_index_get(ele) != index) {
1282                                         err_val = BM_elem_index_get(ele);
1283                                         err_idx = index;
1284                                         is_error = true;
1285                                 }
1286                         }
1287
1288                         BM_elem_index_set(ele, index); /* set_ok */
1289                         index++;
1290                 }
1291
1292                 if ((is_error == true) && (is_dirty == false)) {
1293                         is_any_error = true;
1294                         fprintf(stderr,
1295                                 "Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
1296                                 location, func, type_names[i], err_idx, err_val, msg_a, msg_b);
1297                 }
1298                 else if ((is_error == false) && (is_dirty == true)) {
1299
1300 #if 0       /* mostly annoying */
1301
1302                         /* dirty may have been incorrectly set */
1303                         fprintf(stderr,
1304                                 "Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are correct, '%s', '%s'\n",
1305                                 location, func, type_names[i], msg_a, msg_b);
1306 #endif
1307                 }
1308         }
1309
1310 #if 0 /* mostly annoying, even in debug mode */
1311 #ifdef DEBUG
1312         if (is_any_error == 0) {
1313                 fprintf(stderr,
1314                         "Valid Index Success: at %s, %s, '%s', '%s'\n",
1315                         location, func, msg_a, msg_b);
1316         }
1317 #endif
1318 #endif
1319         (void) is_any_error; /* shut up the compiler */
1320
1321 }
1322
1323 /* debug check only - no need to optimize */
1324 #ifndef NDEBUG
1325 bool BM_mesh_elem_table_check(BMesh *bm)
1326 {
1327         BMIter iter;
1328         BMElem *ele;
1329         int i;
1330
1331         if (bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) {
1332                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
1333                         if (ele != (BMElem *)bm->vtable[i]) {
1334                                 return false;
1335                         }
1336                 }
1337         }
1338
1339         if (bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) {
1340                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
1341                         if (ele != (BMElem *)bm->etable[i]) {
1342                                 return false;
1343                         }
1344                 }
1345         }
1346
1347         if (bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) {
1348                 BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
1349                         if (ele != (BMElem *)bm->ftable[i]) {
1350                                 return false;
1351                         }
1352                 }
1353         }
1354
1355         return true;
1356 }
1357 #endif
1358
1359
1360
1361 void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
1362 {
1363         /* assume if the array is non-null then its valid and no need to recalc */
1364         const char htype_needed = (((bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) ? 0 : BM_VERT) |
1365                                    ((bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) ? 0 : BM_EDGE) |
1366                                    ((bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) ? 0 : BM_FACE)) & htype;
1367
1368         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1369
1370         /* in debug mode double check we didn't need to recalculate */
1371         BLI_assert(BM_mesh_elem_table_check(bm) == true);
1372
1373         if (htype_needed == 0) {
1374                 goto finally;
1375         }
1376
1377         if (htype_needed & BM_VERT) {
1378                 if (bm->vtable && bm->totvert <= bm->vtable_tot && bm->totvert * 2 >= bm->vtable_tot) {
1379                         /* pass (re-use the array) */
1380                 }
1381                 else {
1382                         if (bm->vtable)
1383                                 MEM_freeN(bm->vtable);
1384                         bm->vtable = MEM_mallocN(sizeof(void **) * bm->totvert, "bm->vtable");
1385                         bm->vtable_tot = bm->totvert;
1386                 }
1387         }
1388         if (htype_needed & BM_EDGE) {
1389                 if (bm->etable && bm->totedge <= bm->etable_tot && bm->totedge * 2 >= bm->etable_tot) {
1390                         /* pass (re-use the array) */
1391                 }
1392                 else {
1393                         if (bm->etable)
1394                                 MEM_freeN(bm->etable);
1395                         bm->etable = MEM_mallocN(sizeof(void **) * bm->totedge, "bm->etable");
1396                         bm->etable_tot = bm->totedge;
1397                 }
1398         }
1399         if (htype_needed & BM_FACE) {
1400                 if (bm->ftable && bm->totface <= bm->ftable_tot && bm->totface * 2 >= bm->ftable_tot) {
1401                         /* pass (re-use the array) */
1402                 }
1403                 else {
1404                         if (bm->ftable)
1405                                 MEM_freeN(bm->ftable);
1406                         bm->ftable = MEM_mallocN(sizeof(void **) * bm->totface, "bm->ftable");
1407                         bm->ftable_tot = bm->totface;
1408                 }
1409         }
1410
1411         if (htype_needed & BM_VERT) {
1412                 BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
1413         }
1414
1415         if (htype_needed & BM_EDGE) {
1416                 BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
1417         }
1418
1419         if (htype_needed & BM_FACE) {
1420                 BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
1421         }
1422
1423 finally:
1424         /* Only clear dirty flags when all the pointers and data are actually valid.
1425          * This prevents possible threading issues when dirty flag check failed but
1426          * data wasn't ready still.
1427          */
1428         bm->elem_table_dirty &= ~htype_needed;
1429 }
1430
1431 /* use BM_mesh_elem_table_ensure where possible to avoid full rebuild */
1432 void BM_mesh_elem_table_init(BMesh *bm, const char htype)
1433 {
1434         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1435
1436         /* force recalc */
1437         BM_mesh_elem_table_free(bm, BM_ALL_NOLOOP);
1438         BM_mesh_elem_table_ensure(bm, htype);
1439 }
1440
1441 void BM_mesh_elem_table_free(BMesh *bm, const char htype)
1442 {
1443         if (htype & BM_VERT) {
1444                 MEM_SAFE_FREE(bm->vtable);
1445         }
1446
1447         if (htype & BM_EDGE) {
1448                 MEM_SAFE_FREE(bm->etable);
1449         }
1450
1451         if (htype & BM_FACE) {
1452                 MEM_SAFE_FREE(bm->ftable);
1453         }
1454 }
1455
1456 BMVert *BM_vert_at_index(BMesh *bm, const int index)
1457 {
1458         BLI_assert((index >= 0) && (index < bm->totvert));
1459         BLI_assert((bm->elem_table_dirty & BM_VERT) == 0);
1460         return bm->vtable[index];
1461 }
1462
1463 BMEdge *BM_edge_at_index(BMesh *bm, const int index)
1464 {
1465         BLI_assert((index >= 0) && (index < bm->totedge));
1466         BLI_assert((bm->elem_table_dirty & BM_EDGE) == 0);
1467         return bm->etable[index];
1468 }
1469
1470 BMFace *BM_face_at_index(BMesh *bm, const int index)
1471 {
1472         BLI_assert((index >= 0) && (index < bm->totface));
1473         BLI_assert((bm->elem_table_dirty & BM_FACE) == 0);
1474         return bm->ftable[index];
1475 }
1476
1477
1478 BMVert *BM_vert_at_index_find(BMesh *bm, const int index)
1479 {
1480         return BLI_mempool_findelem(bm->vpool, index);
1481 }
1482
1483 BMEdge *BM_edge_at_index_find(BMesh *bm, const int index)
1484 {
1485         return BLI_mempool_findelem(bm->epool, index);
1486 }
1487
1488 BMFace *BM_face_at_index_find(BMesh *bm, const int index)
1489 {
1490         return BLI_mempool_findelem(bm->fpool, index);
1491 }
1492
1493 /**
1494  * Use lookup table when available, else use slower find functions.
1495  *
1496  * \note Try to use #BM_mesh_elem_table_ensure instead.
1497  */
1498 BMVert *BM_vert_at_index_find_or_table(BMesh *bm, const int index)
1499 {
1500         if ((bm->elem_table_dirty & BM_VERT) == 0) {
1501                 return (index < bm->totvert) ? bm->vtable[index] : NULL;
1502         }
1503         else {
1504                 return BM_vert_at_index_find(bm, index);
1505         }
1506 }
1507
1508 BMEdge *BM_edge_at_index_find_or_table(BMesh *bm, const int index)
1509 {
1510         if ((bm->elem_table_dirty & BM_EDGE) == 0) {
1511                 return (index < bm->totedge) ? bm->etable[index] : NULL;
1512         }
1513         else {
1514                 return BM_edge_at_index_find(bm, index);
1515         }
1516 }
1517
1518 BMFace *BM_face_at_index_find_or_table(BMesh *bm, const int index)
1519 {
1520         if ((bm->elem_table_dirty & BM_FACE) == 0) {
1521                 return (index < bm->totface) ? bm->ftable[index] : NULL;
1522         }
1523         else {
1524                 return BM_face_at_index_find(bm, index);
1525         }
1526 }
1527
1528
1529 /**
1530  * Return the amount of element of type 'type' in a given bmesh.
1531  */
1532 int BM_mesh_elem_count(BMesh *bm, const char htype)
1533 {
1534         BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
1535
1536         switch (htype) {
1537                 case BM_VERT: return bm->totvert;
1538                 case BM_EDGE: return bm->totedge;
1539                 case BM_FACE: return bm->totface;
1540                 default:
1541                 {
1542                         BLI_assert(0);
1543                         return 0;
1544                 }
1545         }
1546 }
1547
1548
1549 /**
1550  * Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
1551  * (xxx_idx[org_index] = new_index).
1552  *
1553  * A NULL array means no changes.
1554  *
1555  * Note: - Does not mess with indices, just sets elem_index_dirty flag.
1556  *       - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
1557  *         on a per-face basis...).
1558  *
1559  * WARNING: Be careful if you keep pointers to affected BM elements, or arrays, when using this func!
1560  */
1561 void BM_mesh_remap(
1562         BMesh *bm,
1563         const uint *vert_idx,
1564         const uint *edge_idx,
1565         const uint *face_idx)
1566 {
1567         /* Mapping old to new pointers. */
1568         GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
1569         BMIter iter, iterl;
1570         BMVert *ve;
1571         BMEdge *ed;
1572         BMFace *fa;
1573         BMLoop *lo;
1574
1575         if (!(vert_idx || edge_idx || face_idx))
1576                 return;
1577
1578         BM_mesh_elem_table_ensure(
1579                 bm,
1580                 (vert_idx ? BM_VERT : 0) |
1581                 (edge_idx ? BM_EDGE : 0) |
1582                 (face_idx ? BM_FACE : 0));
1583
1584         /* Remap Verts */
1585         if (vert_idx) {
1586                 BMVert **verts_pool, *verts_copy, **vep;
1587                 int i, totvert = bm->totvert;
1588                 const uint *new_idx;
1589                 /* Special case: Python uses custom - data layers to hold PyObject references.
1590                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1591                 const int cd_vert_pyptr  = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
1592
1593                 /* Init the old-to-new vert pointers mapping */
1594                 vptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap vert pointers mapping", bm->totvert);
1595
1596                 /* Make a copy of all vertices. */
1597                 verts_pool = bm->vtable;
1598                 verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
1599                 void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
1600                 for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
1601                         *ve = **vep;
1602 /*                      printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
1603                         if (cd_vert_pyptr != -1) {
1604                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
1605                                 pyptrs[i] = *pyptr;
1606                         }
1607                 }
1608
1609                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1610                 new_idx = vert_idx + totvert - 1;
1611                 ve = verts_copy + totvert - 1;
1612                 vep = verts_pool + totvert - 1; /* old, org pointer */
1613                 for (i = totvert; i--; new_idx--, ve--, vep--) {
1614                         BMVert *new_vep = verts_pool[*new_idx];
1615                         *new_vep = *ve;
1616 /*                      printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
1617                         BLI_ghash_insert(vptr_map, *vep, new_vep);
1618                         if (cd_vert_pyptr != -1) {
1619                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
1620                                 *pyptr = pyptrs[*new_idx];
1621                         }
1622                 }
1623                 bm->elem_index_dirty |= BM_VERT;
1624                 bm->elem_table_dirty |= BM_VERT;
1625
1626                 MEM_freeN(verts_copy);
1627                 if (pyptrs) {
1628                         MEM_freeN(pyptrs);
1629                 }
1630         }
1631
1632         /* Remap Edges */
1633         if (edge_idx) {
1634                 BMEdge **edges_pool, *edges_copy, **edp;
1635                 int i, totedge = bm->totedge;
1636                 const uint *new_idx;
1637                 /* Special case: Python uses custom - data layers to hold PyObject references.
1638                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1639                 const int cd_edge_pyptr  = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
1640
1641                 /* Init the old-to-new vert pointers mapping */
1642                 eptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap edge pointers mapping", bm->totedge);
1643
1644                 /* Make a copy of all vertices. */
1645                 edges_pool = bm->etable;
1646                 edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
1647                 void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
1648                 for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
1649                         *ed = **edp;
1650                         if (cd_edge_pyptr != -1) {
1651                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
1652                                 pyptrs[i] = *pyptr;
1653                         }
1654                 }
1655
1656                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1657                 new_idx = edge_idx + totedge - 1;
1658                 ed = edges_copy + totedge - 1;
1659                 edp = edges_pool + totedge - 1; /* old, org pointer */
1660                 for (i = totedge; i--; new_idx--, ed--, edp--) {
1661                         BMEdge *new_edp = edges_pool[*new_idx];
1662                         *new_edp = *ed;
1663                         BLI_ghash_insert(eptr_map, *edp, new_edp);
1664 /*                      printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
1665                         if (cd_edge_pyptr != -1) {
1666                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
1667                                 *pyptr = pyptrs[*new_idx];
1668                         }
1669                 }
1670                 bm->elem_index_dirty |= BM_EDGE;
1671                 bm->elem_table_dirty |= BM_EDGE;
1672
1673                 MEM_freeN(edges_copy);
1674                 if (pyptrs) {
1675                         MEM_freeN(pyptrs);
1676                 }
1677         }
1678
1679         /* Remap Faces */
1680         if (face_idx) {
1681                 BMFace **faces_pool, *faces_copy, **fap;
1682                 int i, totface = bm->totface;
1683                 const uint *new_idx;
1684                 /* Special case: Python uses custom - data layers to hold PyObject references.
1685                  * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
1686                 const int cd_poly_pyptr  = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
1687
1688                 /* Init the old-to-new vert pointers mapping */
1689                 fptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap face pointers mapping", bm->totface);
1690
1691                 /* Make a copy of all vertices. */
1692                 faces_pool = bm->ftable;
1693                 faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
1694                 void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
1695                 for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
1696                         *fa = **fap;
1697                         if (cd_poly_pyptr != -1) {
1698                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
1699                                 pyptrs[i] = *pyptr;
1700                         }
1701                 }
1702
1703                 /* Copy back verts to their new place, and update old2new pointers mapping. */
1704                 new_idx = face_idx + totface - 1;
1705                 fa = faces_copy + totface - 1;
1706                 fap = faces_pool + totface - 1; /* old, org pointer */
1707                 for (i = totface; i--; new_idx--, fa--, fap--) {
1708                         BMFace *new_fap = faces_pool[*new_idx];
1709                         *new_fap = *fa;
1710                         BLI_ghash_insert(fptr_map, *fap, new_fap);
1711                         if (cd_poly_pyptr != -1) {
1712                                 void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
1713                                 *pyptr = pyptrs[*new_idx];
1714                         }
1715                 }
1716
1717                 bm->elem_index_dirty |= BM_FACE | BM_LOOP;
1718                 bm->elem_table_dirty |= BM_FACE;
1719
1720                 MEM_freeN(faces_copy);
1721                 if (pyptrs) {
1722                         MEM_freeN(pyptrs);
1723                 }
1724         }
1725
1726         /* And now, fix all vertices/edges/faces/loops pointers! */
1727         /* Verts' pointers, only edge pointers... */
1728         if (eptr_map) {
1729                 BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
1730 /*                      printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, ve->e));*/
1731                         if (ve->e) {
1732                                 ve->e = BLI_ghash_lookup(eptr_map, ve->e);
1733                                 BLI_assert(ve->e);
1734                         }
1735                 }
1736         }
1737
1738         /* Edges' pointers, only vert pointers (as we don't mess with loops!), and - ack! - edge pointers,
1739          * as we have to handle disklinks... */
1740         if (vptr_map || eptr_map) {
1741                 BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
1742                         if (vptr_map) {
1743 /*                              printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, ed->v1));*/
1744 /*                              printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, ed->v2));*/
1745                                 ed->v1 = BLI_ghash_lookup(vptr_map, ed->v1);
1746                                 ed->v2 = BLI_ghash_lookup(vptr_map, ed->v2);
1747                                 BLI_assert(ed->v1);
1748                                 BLI_assert(ed->v2);
1749                         }
1750                         if (eptr_map) {
1751 /*                              printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
1752 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev));*/
1753 /*                              printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
1754 /*                                     BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next));*/
1755 /*                              printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
1756 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev));*/
1757 /*                              printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
1758 /*                                     BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next));*/
1759                                 ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev);
1760                                 ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next);
1761                                 ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev);
1762                                 ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next);
1763                                 BLI_assert(ed->v1_disk_link.prev);
1764                                 BLI_assert(ed->v1_disk_link.next);
1765                                 BLI_assert(ed->v2_disk_link.prev);
1766                                 BLI_assert(ed->v2_disk_link.next);
1767                         }
1768                 }
1769         }
1770
1771         /* Faces' pointers (loops, in fact), always needed... */
1772         BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
1773                 BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
1774                         if (vptr_map) {
1775 /*                              printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, lo->v));*/
1776                                 lo->v = BLI_ghash_lookup(vptr_map, lo->v);
1777                                 BLI_assert(lo->v);
1778                         }
1779                         if (eptr_map) {
1780 /*                              printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, lo->e));*/
1781                                 lo->e = BLI_ghash_lookup(eptr_map, lo->e);
1782                                 BLI_assert(lo->e);
1783                         }
1784                         if (fptr_map) {
1785 /*                              printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, lo->f));*/
1786                                 lo->f = BLI_ghash_lookup(fptr_map, lo->f);
1787                                 BLI_assert(lo->f);
1788                         }
1789                 }
1790         }
1791
1792         /* Selection history */
1793         {
1794                 BMEditSelection *ese;
1795                 for (ese = bm->selected.first; ese; ese = ese->next) {
1796                         switch (ese->htype) {
1797                                 case BM_VERT:
1798                                         if (vptr_map) {
1799                                                 ese->ele = BLI_ghash_lookup(vptr_map, ese->ele);
1800                                                 BLI_assert(ese->ele);
1801                                         }
1802                                         break;
1803                                 case BM_EDGE:
1804                                         if (eptr_map) {
1805                                                 ese->ele = BLI_ghash_lookup(eptr_map, ese->ele);
1806                                                 BLI_assert(ese->ele);
1807                                         }
1808                                         break;
1809                                 case BM_FACE:
1810                                         if (fptr_map) {
1811                                                 ese->ele = BLI_ghash_lookup(fptr_map, ese->ele);
1812                                                 BLI_assert(ese->ele);
1813                                         }
1814                                         break;
1815                         }
1816                 }
1817         }
1818
1819         if (fptr_map) {
1820                 if (bm->act_face) {
1821                         bm->act_face = BLI_ghash_lookup(fptr_map, bm->act_face);
1822                         BLI_assert(bm->act_face);
1823                 }
1824         }
1825
1826         if (vptr_map)
1827                 BLI_ghash_free(vptr_map, NULL, NULL);
1828         if (eptr_map)
1829                 BLI_ghash_free(eptr_map, NULL, NULL);
1830         if (fptr_map)
1831                 BLI_ghash_free(fptr_map, NULL, NULL);
1832 }
1833
1834 /**
1835  * Use new memory pools for this mesh.
1836  *
1837  * \note needed for re-sizing elements (adding/removing tool flags)
1838  * but could also be used for packing fragmented bmeshes.
1839  */
1840 void BM_mesh_rebuild(
1841         BMesh *bm, const struct BMeshCreateParams *params,
1842         BLI_mempool *vpool_dst, BLI_mempool *epool_dst, BLI_mempool *lpool_dst, BLI_mempool *fpool_dst)
1843 {
1844         const char remap =
1845                 (vpool_dst ? BM_VERT : 0) |
1846                 (epool_dst ? BM_EDGE : 0) |
1847                 (lpool_dst ? BM_LOOP : 0) |
1848                 (fpool_dst ? BM_FACE : 0);
1849
1850         BMVert **vtable_dst = (remap & BM_VERT) ? MEM_mallocN(bm->totvert * sizeof(BMVert *), __func__) : NULL;
1851         BMEdge **etable_dst = (remap & BM_EDGE) ? MEM_mallocN(bm->totedge * sizeof(BMEdge *), __func__) : NULL;
1852         BMLoop **ltable_dst = (remap & BM_LOOP) ? MEM_mallocN(bm->totloop * sizeof(BMLoop *), __func__) : NULL;
1853         BMFace **ftable_dst = (remap & BM_FACE) ? MEM_mallocN(bm->totface * sizeof(BMFace *), __func__) : NULL;
1854
1855         const bool use_toolflags = params->use_toolflags;
1856
1857         if (remap & BM_VERT) {
1858                 BMIter iter;
1859                 int index;
1860                 BMVert *v_src;
1861                 BM_ITER_MESH_INDEX (v_src, &iter, bm, BM_VERTS_OF_MESH, index) {
1862                         BMVert *v_dst = BLI_mempool_alloc(vpool_dst);
1863                         memcpy(v_dst, v_src, sizeof(BMVert));
1864                         if (use_toolflags) {
1865                                 ((BMVert_OFlag *)v_dst)->oflags = bm->vtoolflagpool ? BLI_mempool_calloc(bm->vtoolflagpool) : NULL;
1866                         }
1867
1868                         vtable_dst[index] = v_dst;
1869                         BM_elem_index_set(v_src, index);  /* set_ok */
1870                 }
1871         }
1872
1873         if (remap & BM_EDGE) {
1874                 BMIter iter;
1875                 int index;
1876                 BMEdge *e_src;
1877                 BM_ITER_MESH_INDEX (e_src, &iter, bm, BM_EDGES_OF_MESH, index) {
1878                         BMEdge *e_dst = BLI_mempool_alloc(epool_dst);
1879                         memcpy(e_dst, e_src, sizeof(BMEdge));
1880                         if (use_toolflags) {
1881                                 ((BMEdge_OFlag *)e_dst)->oflags = bm->etoolflagpool ? BLI_mempool_calloc(bm->etoolflagpool) : NULL;
1882                         }
1883
1884                         etable_dst[index] = e_dst;
1885                         BM_elem_index_set(e_src, index);  /* set_ok */
1886                 }
1887         }
1888
1889         if (remap & (BM_LOOP | BM_FACE)) {
1890                 BMIter iter;
1891                 int index, index_loop = 0;
1892                 BMFace *f_src;
1893                 BM_ITER_MESH_INDEX (f_src, &iter, bm, BM_FACES_OF_MESH, index) {
1894
1895                         if (remap & BM_FACE) {
1896                                 BMFace *f_dst = BLI_mempool_alloc(fpool_dst);
1897                                 memcpy(f_dst, f_src, sizeof(BMFace));
1898                                 if (use_toolflags) {
1899                                         ((BMFace_OFlag *)f_dst)->oflags = bm->ftoolflagpool ? BLI_mempool_calloc(bm->ftoolflagpool) : NULL;
1900                                 }
1901
1902                                 ftable_dst[index] = f_dst;
1903                                 BM_elem_index_set(f_src, index);  /* set_ok */
1904                         }
1905
1906                         /* handle loops */
1907                         if (remap & BM_LOOP) {
1908                                 BMLoop *l_iter_src, *l_first_src;
1909                                 l_iter_src = l_first_src = BM_FACE_FIRST_LOOP((BMFace *)f_src);
1910                                 do {
1911                                         BMLoop *l_dst = BLI_mempool_alloc(lpool_dst);
1912                                         memcpy(l_dst, l_iter_src, sizeof(BMLoop));
1913                                         ltable_dst[index_loop] = l_dst;
1914                                         BM_elem_index_set(l_iter_src, index_loop++); /* set_ok */
1915                                 } while ((l_iter_src = l_iter_src->next) != l_first_src);
1916                         }
1917                 }
1918         }
1919
1920 #define MAP_VERT(ele) vtable_dst[BM_elem_index_get(ele)]
1921 #define MAP_EDGE(ele) etable_dst[BM_elem_index_get(ele)]
1922 #define MAP_LOOP(ele) ltable_dst[BM_elem_index_get(ele)]
1923 #define MAP_FACE(ele) ftable_dst[BM_elem_index_get(ele)]
1924
1925 #define REMAP_VERT(ele) { if (remap & BM_VERT) { ele = MAP_VERT(ele); }} ((void)0)
1926 #define REMAP_EDGE(ele) { if (remap & BM_EDGE) { ele = MAP_EDGE(ele); }} ((void)0)
1927 #define REMAP_LOOP(ele) { if (remap & BM_LOOP) { ele = MAP_LOOP(ele); }} ((void)0)
1928 #define REMAP_FACE(ele) { if (remap & BM_FACE) { ele = MAP_FACE(ele); }} ((void)0)
1929
1930         /* verts */
1931         {
1932                 for (int i = 0; i < bm->totvert; i++) {
1933                         BMVert *v = vtable_dst[i];
1934                         if (v->e) {
1935                                 REMAP_EDGE(v->e);
1936                         }
1937                 }
1938         }
1939
1940         /* edges */
1941         {
1942                 for (int i = 0; i < bm->totedge; i++) {
1943                         BMEdge *e = etable_dst[i];
1944                         REMAP_VERT(e->v1);
1945                         REMAP_VERT(e->v2);
1946                         REMAP_EDGE(e->v1_disk_link.next);
1947                         REMAP_EDGE(e->v1_disk_link.prev);
1948                         REMAP_EDGE(e->v2_disk_link.next);
1949                         REMAP_EDGE(e->v2_disk_link.prev);
1950                         if (e->l) {
1951                                 REMAP_LOOP(e->l);
1952                         }
1953                 }
1954         }
1955
1956         /* faces */
1957         {
1958                 for (int i = 0; i < bm->totface; i++) {
1959                         BMFace *f = ftable_dst[i];
1960                         REMAP_LOOP(f->l_first);
1961
1962                         {
1963                                 BMLoop *l_iter, *l_first;
1964                                 l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)f);
1965                                 do {
1966                                         REMAP_VERT(l_iter->v);
1967                                         REMAP_EDGE(l_iter->e);
1968                                         REMAP_FACE(l_iter->f);
1969
1970                                         REMAP_LOOP(l_iter->radial_next);
1971                                         REMAP_LOOP(l_iter->radial_prev);
1972                                         REMAP_LOOP(l_iter->next);
1973                                         REMAP_LOOP(l_iter->prev);
1974                                 } while ((l_iter = l_iter->next) != l_first);
1975                         }
1976                 }
1977         }
1978
1979         for (BMEditSelection *ese = bm->selected.first; ese; ese = ese->next) {
1980                 switch (ese->htype) {
1981                         case BM_VERT:
1982                                 if (remap & BM_VERT) {
1983                                         ese->ele = (BMElem *)MAP_VERT(ese->ele);
1984                                 }
1985                                 break;
1986                         case BM_EDGE:
1987                                 if (remap & BM_EDGE) {
1988                                         ese->ele = (BMElem *)MAP_EDGE(ese->ele);
1989                                 }
1990                                 break;
1991                         case BM_FACE:
1992                                 if (remap & BM_FACE) {
1993                                         ese->ele = (BMElem *)MAP_FACE(ese->ele);
1994                                 }
1995                                 break;
1996                 }
1997         }
1998
1999         if (bm->act_face) {
2000                 REMAP_FACE(bm->act_face);
2001         }
2002
2003 #undef MAP_VERT
2004 #undef MAP_EDGE
2005 #undef MAP_LOOP
2006 #undef MAP_EDGE
2007
2008 #undef REMAP_VERT
2009 #undef REMAP_EDGE
2010 #undef REMAP_LOOP
2011 #undef REMAP_EDGE
2012
2013         /* Cleanup, re-use local tables if the current mesh had tables allocated.
2014          * could use irrespective but it may use more memory then the caller wants (and not be needed). */
2015         if (remap & BM_VERT) {
2016                 if (bm->vtable) {
2017                         SWAP(BMVert **, vtable_dst, bm->vtable);
2018                         bm->vtable_tot = bm->totvert;
2019                         bm->elem_table_dirty &= ~BM_VERT;
2020                 }
2021                 MEM_freeN(vtable_dst);
2022                 BLI_mempool_destroy(bm->vpool);
2023                 bm->vpool = vpool_dst;
2024         }
2025
2026         if (remap & BM_EDGE) {
2027                 if (bm->etable) {
2028                         SWAP(BMEdge **, etable_dst, bm->etable);
2029                         bm->etable_tot = bm->totedge;
2030                         bm->elem_table_dirty &= ~BM_EDGE;
2031                 }
2032                 MEM_freeN(etable_dst);
2033                 BLI_mempool_destroy(bm->epool);
2034                 bm->epool = epool_dst;
2035         }
2036
2037         if (remap & BM_LOOP) {
2038                 /* no loop table */
2039                 MEM_freeN(ltable_dst);
2040                 BLI_mempool_destroy(bm->lpool);
2041                 bm->lpool = lpool_dst;
2042         }
2043
2044         if (remap & BM_FACE) {
2045                 if (bm->ftable) {
2046                         SWAP(BMFace **, ftable_dst, bm->ftable);
2047                         bm->ftable_tot = bm->totface;
2048                         bm->elem_table_dirty &= ~BM_FACE;
2049                 }
2050                 MEM_freeN(ftable_dst);
2051                 BLI_mempool_destroy(bm->fpool);
2052                 bm->fpool = fpool_dst;
2053         }
2054 }
2055
2056 /**
2057  * Re-allocates mesh data with/without toolflags.
2058  */
2059 void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
2060 {
2061         if (bm->use_toolflags == use_toolflags) {
2062                 return;
2063         }
2064
2065         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_BM(bm);
2066
2067         BLI_mempool *vpool_dst = NULL;
2068         BLI_mempool *epool_dst = NULL;
2069         BLI_mempool *fpool_dst = NULL;
2070
2071         bm_mempool_init_ex(
2072                 &allocsize, use_toolflags,
2073                 &vpool_dst, &epool_dst, NULL, &fpool_dst);
2074
2075         if (use_toolflags == false) {
2076                 BLI_mempool_destroy(bm->vtoolflagpool);
2077                 BLI_mempool_destroy(bm->etoolflagpool);
2078                 BLI_mempool_destroy(bm->ftoolflagpool);
2079
2080                 bm->vtoolflagpool = NULL;
2081                 bm->etoolflagpool = NULL;
2082                 bm->ftoolflagpool = NULL;
2083         }
2084
2085         BM_mesh_rebuild(
2086                 bm,
2087                 &((struct BMeshCreateParams){.use_toolflags = use_toolflags,}),
2088                 vpool_dst, epool_dst, NULL, fpool_dst);
2089
2090         bm->use_toolflags = use_toolflags;
2091 }