style cleanup
[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_listbase.h"
35 #include "BLI_math.h"
36 #include "BLI_utildefines.h"
37
38 #include "BKE_cdderivedmesh.h"
39 #include "BKE_tessmesh.h"
40 #include "BKE_multires.h"
41
42 #include "intern/bmesh_private.h"
43
44 /* used as an extern, defined in bmesh.h */
45 const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
46 const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
47
48 static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize)
49 {
50         bm->vpool = BLI_mempool_create(sizeof(BMVert), allocsize->totvert,
51                                        bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
52         bm->epool = BLI_mempool_create(sizeof(BMEdge), allocsize->totedge,
53                                        bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
54         bm->lpool = BLI_mempool_create(sizeof(BMLoop), allocsize->totloop,
55                                        bm_mesh_chunksize_default.totloop, 0);
56         bm->fpool = BLI_mempool_create(sizeof(BMFace), allocsize->totface,
57                                        bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
58
59 #ifdef USE_BMESH_HOLES
60         bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, 0);
61 #endif
62 }
63
64 void BM_mesh_elem_toolflags_ensure(BMesh *bm)
65 {
66         if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
67                 return;
68         }
69
70         bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), max_ii(512, bm->totvert), 512, 0);
71         bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), max_ii(512, bm->totedge), 512, 0);
72         bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), max_ii(512, bm->totface), 512, 0);
73
74 #pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
75         {
76 #pragma omp section
77                 {
78                         BLI_mempool *toolflagpool = bm->vtoolflagpool;
79                         BMIter iter;
80                         BMElemF *ele;
81                         BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
82                                 ele->oflags = BLI_mempool_calloc(toolflagpool);
83                         }
84                 }
85 #pragma omp section
86                 {
87                         BLI_mempool *toolflagpool = bm->etoolflagpool;
88                         BMIter iter;
89                         BMElemF *ele;
90                         BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
91                                 ele->oflags = BLI_mempool_calloc(toolflagpool);
92                         }
93                 }
94 #pragma omp section
95                 {
96                         BLI_mempool *toolflagpool = bm->ftoolflagpool;
97                         BMIter iter;
98                         BMElemF *ele;
99                         BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
100                                 ele->oflags = BLI_mempool_calloc(toolflagpool);
101                         }
102                 }
103         }
104
105
106         bm->totflags = 1;
107 }
108
109 void BM_mesh_elem_toolflags_clear(BMesh *bm)
110 {
111         if (bm->vtoolflagpool) {
112                 BLI_mempool_destroy(bm->vtoolflagpool);
113                 bm->vtoolflagpool = NULL;
114         }
115         if (bm->etoolflagpool) {
116                 BLI_mempool_destroy(bm->etoolflagpool);
117                 bm->etoolflagpool = NULL;
118         }
119         if (bm->ftoolflagpool) {
120                 BLI_mempool_destroy(bm->ftoolflagpool);
121                 bm->ftoolflagpool = NULL;
122         }
123 }
124
125 /**
126  * \brief BMesh Make Mesh
127  *
128  * Allocates a new BMesh structure.
129  *
130  * \return The New bmesh
131  *
132  * \note ob is needed by multires
133  */
134 BMesh *BM_mesh_create(const BMAllocTemplate *allocsize)
135 {
136         /* allocate the structure */
137         BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
138         
139         /* allocate the memory pools for the mesh elements */
140         bm_mempool_init(bm, allocsize);
141
142         /* allocate one flag pool that we don't get rid of. */
143         bm->stackdepth = 1;
144         bm->totflags = 0;
145
146         CustomData_reset(&bm->vdata);
147         CustomData_reset(&bm->edata);
148         CustomData_reset(&bm->ldata);
149         CustomData_reset(&bm->pdata);
150
151         return bm;
152 }
153
154 /**
155  * \brief BMesh Free Mesh Data
156  *
157  *      Frees a BMesh structure.
158  *
159  * \note frees mesh, but not actual BMesh struct
160  */
161 void BM_mesh_data_free(BMesh *bm)
162 {
163         BMVert *v;
164         BMEdge *e;
165         BMLoop *l;
166         BMFace *f;
167         
168
169         BMIter iter;
170         BMIter itersub;
171         
172         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
173                 CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
174         }
175         BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
176                 CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
177         }
178         BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
179                 CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
180                 BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
181                         CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
182                 }
183         }
184
185         /* Free custom data pools, This should probably go in CustomData_free? */
186         if (bm->vdata.totlayer) BLI_mempool_destroy(bm->vdata.pool);
187         if (bm->edata.totlayer) BLI_mempool_destroy(bm->edata.pool);
188         if (bm->ldata.totlayer) BLI_mempool_destroy(bm->ldata.pool);
189         if (bm->pdata.totlayer) BLI_mempool_destroy(bm->pdata.pool);
190
191         /* free custom data */
192         CustomData_free(&bm->vdata, 0);
193         CustomData_free(&bm->edata, 0);
194         CustomData_free(&bm->ldata, 0);
195         CustomData_free(&bm->pdata, 0);
196
197         /* destroy element pools */
198         BLI_mempool_destroy(bm->vpool);
199         BLI_mempool_destroy(bm->epool);
200         BLI_mempool_destroy(bm->lpool);
201         BLI_mempool_destroy(bm->fpool);
202
203         /* destroy flag pool */
204         BM_mesh_elem_toolflags_clear(bm);
205
206 #ifdef USE_BMESH_HOLES
207         BLI_mempool_destroy(bm->looplistpool);
208 #endif
209
210         BLI_freelistN(&bm->selected);
211
212         BMO_error_clear(bm);
213 }
214
215 /**
216  * \brief BMesh Clear Mesh
217  *
218  * Clear all data in bm
219  */
220 void BM_mesh_clear(BMesh *bm)
221 {
222         /* free old mesh */
223         BM_mesh_data_free(bm);
224         memset(bm, 0, sizeof(BMesh));
225
226         /* allocate the memory pools for the mesh elements */
227         bm_mempool_init(bm, &bm_mesh_allocsize_default);
228
229         bm->stackdepth = 1;
230         bm->totflags = 1;
231
232         CustomData_reset(&bm->vdata);
233         CustomData_reset(&bm->edata);
234         CustomData_reset(&bm->ldata);
235         CustomData_reset(&bm->pdata);
236 }
237
238 /**
239  * \brief BMesh Free Mesh
240  *
241  *      Frees a BMesh data and its structure.
242  */
243 void BM_mesh_free(BMesh *bm)
244 {
245         BM_mesh_data_free(bm);
246
247         if (bm->py_handle) {
248                 /* keep this out of 'BM_mesh_data_free' because we want python
249                  * to be able to clear the mesh and maintain access. */
250                 bpy_bm_generic_invalidate(bm->py_handle);
251                 bm->py_handle = NULL;
252         }
253
254         MEM_freeN(bm);
255 }
256
257 /**
258  * \brief BMesh Compute Normals
259  *
260  * Updates the normals of a mesh.
261  */
262 void BM_mesh_normals_update(BMesh *bm, const bool skip_hidden)
263 {
264         BMVert *v;
265         BMFace *f;
266         BMLoop *l;
267         BMEdge *e;
268         BMIter verts;
269         BMIter faces;
270         BMIter loops;
271         BMIter edges;
272         int index;
273         float (*edgevec)[3];
274         
275         /* calculate all face normals */
276         BM_ITER_MESH (f, &faces, bm, BM_FACES_OF_MESH) {
277                 if (skip_hidden && BM_elem_flag_test(f, BM_ELEM_HIDDEN))
278                         continue;
279 #if 0   /* UNUSED */
280                 if (f->head.flag & BM_NONORMCALC)
281                         continue;
282 #endif
283
284                 BM_face_normal_update(f);
285         }
286         
287         /* Zero out vertex normals */
288         BM_ITER_MESH (v, &verts, bm, BM_VERTS_OF_MESH) {
289                 if (skip_hidden && BM_elem_flag_test(v, BM_ELEM_HIDDEN))
290                         continue;
291
292                 zero_v3(v->no);
293         }
294
295         /* compute normalized direction vectors for each edge. directions will be
296          * used below for calculating the weights of the face normals on the vertex
297          * normals */
298         index = 0;
299         edgevec = MEM_callocN(sizeof(float) * 3 * bm->totedge, "BM normal computation array");
300         BM_ITER_MESH (e, &edges, bm, BM_EDGES_OF_MESH) {
301                 BM_elem_index_set(e, index); /* set_inline */
302
303                 if (e->l) {
304                         sub_v3_v3v3(edgevec[index], e->v2->co, e->v1->co);
305                         normalize_v3(edgevec[index]);
306                 }
307                 else {
308                         /* the edge vector will not be needed when the edge has no radial */
309                 }
310
311                 index++;
312         }
313         bm->elem_index_dirty &= ~BM_EDGE;
314
315         /* add weighted face normals to vertices */
316         BM_ITER_MESH (f, &faces, bm, BM_FACES_OF_MESH) {
317
318                 if (skip_hidden && BM_elem_flag_test(f, BM_ELEM_HIDDEN))
319                         continue;
320
321                 BM_ITER_ELEM (l, &loops, f, BM_LOOPS_OF_FACE) {
322                         float *e1diff, *e2diff;
323                         float dotprod;
324                         float fac;
325
326                         /* calculate the dot product of the two edges that
327                          * meet at the loop's vertex */
328                         e1diff = edgevec[BM_elem_index_get(l->prev->e)];
329                         e2diff = edgevec[BM_elem_index_get(l->e)];
330                         dotprod = dot_v3v3(e1diff, e2diff);
331
332                         /* edge vectors are calculated from e->v1 to e->v2, so
333                          * adjust the dot product if one but not both loops
334                          * actually runs from from e->v2 to e->v1 */
335                         if ((l->prev->e->v1 == l->prev->v) ^ (l->e->v1 == l->v)) {
336                                 dotprod = -dotprod;
337                         }
338
339                         fac = saacos(-dotprod);
340
341                         /* accumulate weighted face normal into the vertex's normal */
342                         madd_v3_v3fl(l->v->no, f->no, fac);
343                 }
344         }
345         
346         /* normalize the accumulated vertex normals */
347         BM_ITER_MESH (v, &verts, bm, BM_VERTS_OF_MESH) {
348                 if (skip_hidden && BM_elem_flag_test(v, BM_ELEM_HIDDEN))
349                         continue;
350
351                 if (UNLIKELY(normalize_v3(v->no) == 0.0f)) {
352                         normalize_v3_v3(v->no, v->co);
353                 }
354         }
355         
356         MEM_freeN(edgevec);
357 }
358
359 static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from, int to)
360 {
361         /* switch multires data out of tangent space */
362         if (CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
363                 BMEditMesh *em = BMEdit_Create(bm, false);
364                 DerivedMesh *dm = CDDM_from_editbmesh(em, true, false);
365                 MDisps *mdisps;
366                 BMFace *f;
367                 BMIter iter;
368                 // int i = 0; // UNUSED
369                 
370                 multires_set_space(dm, ob, from, to);
371                 
372                 mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS);
373                 
374                 BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
375                         BMLoop *l;
376                         BMIter liter;
377                         BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
378                                 MDisps *lmd = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_MDISPS);
379                                 
380                                 if (!lmd->disps) {
381                                         printf("%s: warning - 'lmd->disps' == NULL\n", __func__);
382                                 }
383                                 
384                                 if (lmd->disps && lmd->totdisp == mdisps->totdisp) {
385                                         memcpy(lmd->disps, mdisps->disps, sizeof(float) * 3 * lmd->totdisp);
386                                 }
387                                 else if (mdisps->disps) {
388                                         if (lmd->disps)
389                                                 MEM_freeN(lmd->disps);
390                                         
391                                         lmd->disps = MEM_dupallocN(mdisps->disps);
392                                         lmd->totdisp = mdisps->totdisp;
393                                         lmd->level = mdisps->level;
394                                 }
395                                 
396                                 mdisps++;
397                                 // i += 1;
398                         }
399                 }
400                 
401                 dm->needsFree = 1;
402                 dm->release(dm);
403                 
404                 /* setting this to NULL prevents BMEdit_Free from freeing it */
405                 em->bm = NULL;
406                 BMEdit_Free(em);
407                 MEM_freeN(em);
408         }
409 }
410
411 /**
412  * \brief BMesh Begin Edit
413  *
414  * Functions for setting up a mesh for editing and cleaning up after
415  * the editing operations are done. These are called by the tools/operator
416  * API for each time a tool is executed.
417  */
418 void bmesh_edit_begin(BMesh *UNUSED(bm), int UNUSED(type_flag))
419 {
420         /* Most operators seem to be using BMO_OP_FLAG_UNTAN_MULTIRES to change the MDisps to
421          * absolute space during mesh edits. With this enabled, changes to the topology
422          * (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
423          * the mesh at all, which doesn't seem right. Turning off completely for now,
424          * until this is shown to be better for certain types of mesh edits. */
425 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
426         /* switch multires data out of tangent space */
427         if ((type_flag & BMO_OP_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
428                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
429
430                 /* ensure correct normals, if possible */
431                 bmesh_rationalize_normals(bm, 0);
432                 BM_mesh_normals_update(bm);
433         }
434 #endif
435 }
436
437 /**
438  * \brief BMesh End Edit
439  */
440 void bmesh_edit_end(BMesh *bm, int UNUSED(flag))
441 {
442         /* BMO_OP_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
443 #ifdef BMOP_UNTAN_MULTIRES_ENABLED
444         /* switch multires data into tangent space */
445         if ((flag & BMO_OP_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
446                 /* set normals to their previous winding */
447                 bmesh_rationalize_normals(bm, 1);
448                 bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
449         }
450         else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
451                 bmesh_rationalize_normals(bm, 1);
452         }
453 #endif
454
455         /* compute normals, clear temp flags and flush selections */
456         BM_mesh_normals_update(bm, true);
457         BM_mesh_select_mode_flush(bm);
458 }
459
460 void BM_mesh_elem_index_ensure(BMesh *bm, const char hflag)
461 {
462 #ifdef DEBUG
463         BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
464 #endif
465
466 #pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
467         {
468 #pragma omp section
469                 {
470                         if (hflag & BM_VERT) {
471                                 if (bm->elem_index_dirty & BM_VERT) {
472                                         BMIter iter;
473                                         BMElem *ele;
474
475                                         int index;
476                                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
477                                                 BM_elem_index_set(ele, index); /* set_ok */
478                                         }
479                                         BLI_assert(index == bm->totvert);
480                                 }
481                                 else {
482                                         // printf("%s: skipping vert index calc!\n", __func__);
483                                 }
484                         }
485                 }
486
487 #pragma omp section
488                 {
489                         if (hflag & BM_EDGE) {
490                                 if (bm->elem_index_dirty & BM_EDGE) {
491                                         BMIter iter;
492                                         BMElem *ele;
493
494                                         int index;
495                                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
496                                                 BM_elem_index_set(ele, index); /* set_ok */
497                                         }
498                                         BLI_assert(index == bm->totedge);
499                                 }
500                                 else {
501                                         // printf("%s: skipping edge index calc!\n", __func__);
502                                 }
503                         }
504                 }
505
506 #pragma omp section
507                 {
508                         if (hflag & BM_FACE) {
509                                 if (bm->elem_index_dirty & BM_FACE) {
510                                         BMIter iter;
511                                         BMElem *ele;
512
513                                         int index;
514                                         BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
515                                                 BM_elem_index_set(ele, index); /* set_ok */
516                                         }
517                                         BLI_assert(index == bm->totface);
518                                 }
519                                 else {
520                                         // printf("%s: skipping face index calc!\n", __func__);
521                                 }
522                         }
523                 }
524         }
525
526         bm->elem_index_dirty &= ~hflag;
527 }
528
529
530 /**
531  * Array checking/setting macros
532  *
533  * Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
534  *
535  * To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
536  * this flag is set incorrectly which could crash blender.
537  *
538  * These functions ensure its correct and are called more often in debug mode.
539  */
540
541 void BM_mesh_elem_index_validate(BMesh *bm, const char *location, const char *func,
542                                  const char *msg_a, const char *msg_b)
543 {
544         const char iter_types[3] = {BM_VERTS_OF_MESH,
545                                     BM_EDGES_OF_MESH,
546                                     BM_FACES_OF_MESH};
547
548         const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
549         const char *type_names[3] = {"vert", "edge", "face"};
550
551         BMIter iter;
552         BMElem *ele;
553         int i;
554         bool is_any_error = 0;
555
556         for (i = 0; i < 3; i++) {
557                 const bool is_dirty = (flag_types[i] & bm->elem_index_dirty);
558                 int index = 0;
559                 bool is_error = false;
560                 int err_val = 0;
561                 int err_idx = 0;
562
563                 BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
564                         if (!is_dirty) {
565                                 if (BM_elem_index_get(ele) != index) {
566                                         err_val = BM_elem_index_get(ele);
567                                         err_idx = index;
568                                         is_error = true;
569                                 }
570                         }
571
572                         BM_elem_index_set(ele, index); /* set_ok */
573                         index++;
574                 }
575
576                 if ((is_error == true) && (is_dirty == false)) {
577                         is_any_error = true;
578                         fprintf(stderr,
579                                 "Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
580                                 location, func, type_names[i], err_idx, err_val, msg_a, msg_b);
581                 }
582                 else if ((is_error == false) && (is_dirty == true)) {
583
584 #if 0       /* mostly annoying */
585
586                         /* dirty may have been incorrectly set */
587                         fprintf(stderr,
588                                 "Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are correct, '%s', '%s'\n",
589                                 location, func, type_names[i], msg_a, msg_b);
590 #endif
591                 }
592         }
593
594 #if 0 /* mostly annoying, even in debug mode */
595 #ifdef DEBUG
596         if (is_any_error == 0) {
597                 fprintf(stderr,
598                         "Valid Index Success: at %s, %s, '%s', '%s'\n",
599                         location, func, msg_a, msg_b);
600         }
601 #endif
602 #endif
603         (void) is_any_error; /* shut up the compiler */
604
605 }
606
607 /**
608  * Return the amount of element of type 'type' in a given bmesh.
609  */
610 int BM_mesh_elem_count(BMesh *bm, const char htype)
611 {
612         if (htype == BM_VERT) return bm->totvert;
613         else if (htype == BM_EDGE) return bm->totedge;
614         else if (htype == BM_FACE) return bm->totface;
615
616         return 0;
617 }
618
619 /**
620  * Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
621  * (xxx_idx[org_index] = new_index).
622  *
623  * A NULL array means no changes.
624  *
625  * Note: - Does not mess with indices, just sets elem_index_dirty flag.
626  *       - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
627  *         on a per-face basis...).
628  *
629  * WARNING: Be careful if you keep pointers to affected BM elements, or arrays, when using this func!
630  */
631 void BM_mesh_remap(BMesh *bm, int *vert_idx, int *edge_idx, int *face_idx)
632 {
633         /* Mapping old to new pointers. */
634         GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
635         BMIter iter, iterl;
636         BMVert *ve;
637         BMEdge *ed;
638         BMFace *fa;
639         BMLoop *lo;
640
641         if (!(vert_idx || edge_idx || face_idx))
642                 return;
643
644         /* Remap vertices */
645         if (vert_idx) {
646                 BMVert **verts_pool, *verts_copy, **vep;
647                 int i, totvert = bm->totvert;
648                 int *new_idx = NULL;
649
650                 /* Init the old-to-new vert pointers mapping */
651                 vptr_map = BLI_ghash_ptr_new("BM_mesh_remap vert pointers mapping");
652
653                 /* Make a copy of all vertices. */
654                 verts_pool = MEM_callocN(sizeof(BMVert *) * totvert, "BM_mesh_remap verts pool");
655                 BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)verts_pool, totvert);
656                 verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
657                 for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
658                         *ve = **vep;
659 /*                      printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
660                 }
661
662                 /* Copy back verts to their new place, and update old2new pointers mapping. */
663                 new_idx = vert_idx + totvert - 1;
664                 ve = verts_copy + totvert - 1;
665                 vep = verts_pool + totvert - 1; /* old, org pointer */
666                 for (i = totvert; i--; new_idx--, ve--, vep--) {
667                         BMVert *new_vep = verts_pool[*new_idx];
668                         *new_vep = *ve;
669 /*                      printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
670                         BLI_ghash_insert(vptr_map, (void *)*vep, (void *)new_vep);
671                 }
672                 bm->elem_index_dirty |= BM_VERT;
673
674                 MEM_freeN(verts_pool);
675                 MEM_freeN(verts_copy);
676         }
677
678         /* XXX Code not tested yet (though I don't why it would fail)! */
679         if (edge_idx) {
680                 BMEdge **edges_pool, *edges_copy, **edp;
681                 int i, totedge = bm->totedge;
682                 int *new_idx = NULL;
683
684                 /* Init the old-to-new vert pointers mapping */
685                 eptr_map = BLI_ghash_ptr_new("BM_mesh_remap edge pointers mapping");
686
687                 /* Make a copy of all vertices. */
688                 edges_pool = MEM_callocN(sizeof(BMEdge *) * totedge, "BM_mesh_remap edges pool");
689                 BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)edges_pool, totedge);
690                 edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
691                 for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
692                         *ed = **edp;
693                 }
694
695                 /* Copy back verts to their new place, and update old2new pointers mapping. */
696                 new_idx = edge_idx + totedge - 1;
697                 ed = edges_copy + totedge - 1;
698                 edp = edges_pool + totedge - 1; /* old, org pointer */
699                 for (i = totedge; i--; new_idx--, ed--, edp--) {
700                         BMEdge *new_edp = edges_pool[*new_idx];
701                         *new_edp = *ed;
702                         BLI_ghash_insert(eptr_map, (void *)*edp, (void *)new_edp);
703 /*                      printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
704                 }
705                 bm->elem_index_dirty |= BM_EDGE;
706
707                 MEM_freeN(edges_pool);
708                 MEM_freeN(edges_copy);
709         }
710
711         /* XXX Code not tested yet (though I don't why it would fail)! */
712         if (face_idx) {
713                 BMFace **faces_pool, *faces_copy, **fap;
714                 int i, totface = bm->totface;
715                 int *new_idx = NULL;
716
717                 /* Init the old-to-new vert pointers mapping */
718                 fptr_map = BLI_ghash_ptr_new("BM_mesh_remap face pointers mapping");
719
720                 /* Make a copy of all vertices. */
721                 faces_pool = MEM_callocN(sizeof(BMFace *) * totface, "BM_mesh_remap faces pool");
722                 BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)faces_pool, totface);
723                 faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
724                 for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
725                         *fa = **fap;
726                 }
727
728                 /* Copy back verts to their new place, and update old2new pointers mapping. */
729                 new_idx = face_idx + totface - 1;
730                 fa = faces_copy + totface - 1;
731                 fap = faces_pool + totface - 1; /* old, org pointer */
732                 for (i = totface; i--; new_idx--, fa--, fap--) {
733                         BMFace *new_fap = faces_pool[*new_idx];
734                         *new_fap = *fa;
735                         BLI_ghash_insert(fptr_map, (void *)*fap, (void *)new_fap);
736                 }
737
738                 bm->elem_index_dirty |= BM_FACE;
739
740                 MEM_freeN(faces_pool);
741                 MEM_freeN(faces_copy);
742         }
743
744         /* And now, fix all vertices/edges/faces/loops pointers! */
745         /* Verts' pointers, only edge pointers... */
746         if (eptr_map) {
747                 BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
748 /*                      printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, (const void *)ve->e));*/
749                         ve->e = BLI_ghash_lookup(eptr_map, (const void *)ve->e);
750                 }
751         }
752
753         /* Edges' pointers, only vert pointers (as we don't mess with loops!), and - ack! - edge pointers,
754          * as we have to handle disklinks... */
755         if (vptr_map || eptr_map) {
756                 BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
757                         if (vptr_map) {
758 /*                              printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, (const void *)ed->v1));*/
759 /*                              printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, (const void *)ed->v2));*/
760                                 ed->v1 = BLI_ghash_lookup(vptr_map, (const void *)ed->v1);
761                                 ed->v2 = BLI_ghash_lookup(vptr_map, (const void *)ed->v2);
762                         }
763                         if (eptr_map) {
764 /*                              printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
765 /*                                     BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.prev));*/
766 /*                              printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
767 /*                                     BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.next));*/
768 /*                              printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
769 /*                                     BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.prev));*/
770 /*                              printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
771 /*                                     BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.next));*/
772                                 ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.prev);
773                                 ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, (const void *)ed->v1_disk_link.next);
774                                 ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.prev);
775                                 ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, (const void *)ed->v2_disk_link.next);
776                         }
777                 }
778         }
779
780         /* Faces' pointers (loops, in fact), always needed... */
781         BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
782                 BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
783                         if (vptr_map) {
784 /*                              printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, (const void *)lo->v));*/
785                                 lo->v = BLI_ghash_lookup(vptr_map, (const void *)lo->v);
786                         }
787                         if (eptr_map) {
788 /*                              printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, (const void *)lo->e));*/
789                                 lo->e = BLI_ghash_lookup(eptr_map, (const void *)lo->e);
790                         }
791                         if (fptr_map) {
792 /*                              printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, (const void *)lo->f));*/
793                                 lo->f = BLI_ghash_lookup(fptr_map, (const void *)lo->f);
794                         }
795                 }
796         }
797
798         if (vptr_map)
799                 BLI_ghash_free(vptr_map, NULL, NULL);
800         if (eptr_map)
801                 BLI_ghash_free(eptr_map, NULL, NULL);
802         if (fptr_map)
803                 BLI_ghash_free(fptr_map, NULL, NULL);
804 }
805
806 BMVert *BM_vert_at_index(BMesh *bm, const int index)
807 {
808         return BLI_mempool_findelem(bm->vpool, index);
809 }
810
811 BMEdge *BM_edge_at_index(BMesh *bm, const int index)
812 {
813         return BLI_mempool_findelem(bm->epool, index);
814 }
815
816 BMFace *BM_face_at_index(BMesh *bm, const int index)
817 {
818         return BLI_mempool_findelem(bm->fpool, index);
819 }