svn merge -r41722:41723 ^/trunk/blender
[blender.git] / source / blender / editors / mesh / meshtools.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2004 by Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/mesh/meshtools.c
29  *  \ingroup edmesh
30  */
31
32
33 /*
34         meshtools.c: no editmode (violated already :), tools operating on meshes
35 */
36
37 #include <stddef.h>
38 #include <stdlib.h>
39 #include <math.h>
40 #include <float.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_key_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_meshdata_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_utildefines.h"
53 #include "BLI_editVert.h"
54 #include "BLI_ghash.h"
55 #include "BLI_rand.h" /* for randome face sorting */
56 #include "BLI_threads.h"
57
58
59 #include "BKE_context.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_deform.h"
62 #include "BKE_DerivedMesh.h"
63 #include "BKE_key.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_mesh.h"
67 #include "BKE_material.h"
68 #include "BKE_report.h"
69 #include "BKE_tessmesh.h"
70 #include "BKE_multires.h"
71
72 #include "BLO_sys_types.h" // for intptr_t support
73
74 #include "ED_mesh.h"
75 #include "ED_object.h"
76 #include "ED_view3d.h"
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 /* own include */
82 #include "mesh_intern.h"
83 #include "uvedit_intern.h"
84
85 /* * ********************** no editmode!!! *********** */
86
87 /*********************** JOIN ***************************/
88
89 /* join selected meshes into the active mesh, context sensitive
90 return 0 if no join is made (error) and 1 if the join is done */
91
92 int join_mesh_exec(bContext *C, wmOperator *op)
93 {
94         Main *bmain= CTX_data_main(C);
95         Scene *scene= CTX_data_scene(C);
96         Object *ob= CTX_data_active_object(C);
97         Material **matar, *ma;
98         Mesh *me;
99         MVert *mvert, *mv;
100         MEdge *medge = NULL;
101         MFace *mface = NULL;
102         MPoly *mpoly = NULL;
103         MLoop *mloop = NULL;
104         Key *key, *nkey=NULL;
105         KeyBlock *kb, *okb, *kbn;
106         float imat[4][4], cmat[4][4], *fp1, *fp2, curpos;
107         int a, b, totcol, totmat=0, totedge=0, totvert=0, totface=0, ok=0;
108         int totloop=0, totpoly=0, vertofs, *matmap=NULL;
109         int i, j, index, haskey=0, edgeofs, faceofs, loopofs, polyofs;
110         bDeformGroup *dg, *odg;
111         MDeformVert *dvert;
112         CustomData vdata, edata, fdata, ldata, pdata;
113
114         if(scene->obedit) {
115                 BKE_report(op->reports, RPT_WARNING, "Cant join while in editmode");
116                 return OPERATOR_CANCELLED;
117         }
118         
119         /* ob is the object we are adding geometry to */
120         if(!ob || ob->type!=OB_MESH) {
121                 BKE_report(op->reports, RPT_WARNING, "Active object is not a mesh");
122                 return OPERATOR_CANCELLED;
123         }
124         
125         /* count & check */
126         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
127                 if(base->object->type==OB_MESH) {
128                         me= base->object->data;
129                         
130                         totvert+= me->totvert;
131                         totedge+= me->totedge;
132                         totface+= me->totface;
133                         totloop+= me->totloop;
134                         totpoly+= me->totpoly;
135                         totmat+= base->object->totcol;
136                         
137                         if(base->object == ob)
138                                 ok= 1;
139                         
140                         /* check for shapekeys */
141                         if(me->key)
142                                 haskey++;
143                 }
144         }
145         CTX_DATA_END;
146         
147         /* that way the active object is always selected */ 
148         if(ok==0) {
149                 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected mesh");
150                 return OPERATOR_CANCELLED;
151         }
152         
153         /* only join meshes if there are verts to join, there aren't too many, and we only had one mesh selected */
154         me= (Mesh *)ob->data;
155         key= me->key;
156
157         if(totvert==0 || totvert==me->totvert) {
158                 BKE_report(op->reports, RPT_WARNING, "No mesh data to join");
159                 return OPERATOR_CANCELLED;
160         }
161         
162         if(totvert > MESH_MAX_VERTS) {
163                 BKE_reportf(op->reports, RPT_WARNING, "Joining results in %d vertices, limit is " STRINGIFY(MESH_MAX_VERTS), totvert);
164                 return OPERATOR_CANCELLED;              
165         }
166
167         /* new material indices and material array */
168         matar= MEM_callocN(sizeof(void*)*totmat, "join_mesh matar");
169         if (totmat) matmap= MEM_callocN(sizeof(int)*totmat, "join_mesh matmap");
170         totcol= ob->totcol;
171         
172         /* obact materials in new main array, is nicer start! */
173         for(a=0; a<ob->totcol; a++) {
174                 matar[a]= give_current_material(ob, a+1);
175                 id_us_plus((ID *)matar[a]);
176                 /* increase id->us : will be lowered later */
177         }
178         
179         /* - if destination mesh had shapekeys, move them somewhere safe, and set up placeholders
180          *      with arrays that are large enough to hold shapekey data for all meshes
181          * -    if destination mesh didn't have shapekeys, but we encountered some in the meshes we're 
182          *      joining, set up a new keyblock and assign to the mesh
183          */
184         if(key) {
185                 /* make a duplicate copy that will only be used here... (must remember to free it!) */
186                 nkey= copy_key(key);
187                 
188                 /* for all keys in old block, clear data-arrays */
189                 for(kb= key->block.first; kb; kb= kb->next) {
190                         if(kb->data) MEM_freeN(kb->data);
191                         kb->data= MEM_callocN(sizeof(float)*3*totvert, "join_shapekey");
192                         kb->totelem= totvert;
193                         kb->weights= NULL;
194                 }
195         }
196         else if(haskey) {
197                 /* add a new key-block and add to the mesh */
198                 key= me->key= add_key((ID *)me);
199                 key->type = KEY_RELATIVE;
200         }
201         
202         /* first pass over objects - copying materials and vertexgroups across */
203         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
204                 /* only act if a mesh, and not the one we're joining to */
205                 if((ob!=base->object) && (base->object->type==OB_MESH)) {
206                         me= base->object->data;
207                         
208                         /* Join this object's vertex groups to the base one's */
209                         for(dg=base->object->defbase.first; dg; dg=dg->next) {
210                                 /* See if this group exists in the object (if it doesn't, add it to the end) */
211                                 if(!defgroup_find_name(ob, dg->name)) {
212                                         odg = MEM_callocN(sizeof(bDeformGroup), "join deformGroup");
213                                         memcpy(odg, dg, sizeof(bDeformGroup));
214                                         BLI_addtail(&ob->defbase, odg);
215                                 }
216                         }
217                         if(ob->defbase.first && ob->actdef==0)
218                                 ob->actdef=1;
219                         
220                         
221                         if(me->totvert) {
222                                 /* Add this object's materials to the base one's if they don't exist already (but only if limits not exceeded yet) */
223                                 if(totcol < MAXMAT) {
224                                         for(a=1; a<=base->object->totcol; a++) {
225                                                 ma= give_current_material(base->object, a);
226
227                                                 for(b=0; b<totcol; b++) {
228                                                         if(ma == matar[b]) break;
229                                                 }
230                                                 if(b==totcol) {
231                                                         matar[b]= ma;
232                                                         if(ma) {
233                                                                 id_us_plus(&ma->id);
234                                                         }
235                                                         totcol++;
236                                                 }
237                                                 if(totcol >= MAXMAT)
238                                                         break;
239                                         }
240                                 }
241                                 
242                                 /* if this mesh has shapekeys, check if destination mesh already has matching entries too */
243                                 if(me->key && key) {
244                                         for(kb= me->key->block.first; kb; kb= kb->next) {
245                                                 /* if key doesn't exist in destination mesh, add it */
246                                                 if(key_get_named_keyblock(key, kb->name) == NULL) {
247                                                         /* copy this existing one over to the new shapekey block */
248                                                         kbn= MEM_dupallocN(kb);
249                                                         kbn->prev= kbn->next= NULL;
250                                                         
251                                                         /* adjust adrcode and other settings to fit (allocate a new data-array) */
252                                                         kbn->data= MEM_callocN(sizeof(float)*3*totvert, "joined_shapekey");
253                                                         kbn->totelem= totvert;
254                                                         kbn->weights= NULL;
255                                                         
256                                                         okb= key->block.last;
257                                                         curpos= (okb) ? okb->pos : -0.1f;
258                                                         if(key->type == KEY_RELATIVE)
259                                                                 kbn->pos= curpos + 0.1f;
260                                                         else
261                                                                 kbn->pos= curpos;
262                                                         
263                                                         BLI_addtail(&key->block, kbn);
264                                                         kbn->adrcode= key->totkey;
265                                                         key->totkey++;
266                                                         if(key->totkey==1) key->refkey= kbn;
267                                                         
268                                                         // XXX 2.5 Animato
269 #if 0
270                                                         /* also, copy corresponding ipo-curve to ipo-block if applicable */
271                                                         if(me->key->ipo && key->ipo) {
272                                                                 // FIXME... this is a luxury item!
273                                                                 puts("FIXME: ignoring IPO's when joining shapekeys on Meshes for now...");
274                                                         }
275 #endif
276                                                 }
277                                         }
278                                 }
279                         }
280                 }
281         }
282         CTX_DATA_END;
283         
284         /* setup new data for destination mesh */
285         memset(&vdata, 0, sizeof(vdata));
286         memset(&edata, 0, sizeof(edata));
287         memset(&fdata, 0, sizeof(fdata));
288         memset(&ldata, 0, sizeof(ldata));
289         memset(&pdata, 0, sizeof(pdata));
290         
291         mvert= CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
292         medge= CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
293         mface= CustomData_add_layer(&fdata, CD_MFACE, CD_CALLOC, NULL, totface);
294         mloop= CustomData_add_layer(&ldata, CD_MLOOP, CD_CALLOC, NULL, totloop);
295         mpoly= CustomData_add_layer(&pdata, CD_MPOLY, CD_CALLOC, NULL, totpoly);
296
297         vertofs= 0;
298         edgeofs= 0;
299         faceofs= 0;
300         loopofs= 0;
301         polyofs= 0;
302         
303         /* inverse transform for all selected meshes in this object */
304         invert_m4_m4(imat, ob->obmat);
305         
306         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
307                 /* only join if this is a mesh */
308                 if(base->object->type==OB_MESH) {
309                         me= base->object->data;
310                         
311                         if(me->totvert) {
312                                 /* standard data */
313                                 CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
314                                 CustomData_copy_data(&me->vdata, &vdata, 0, vertofs, me->totvert);
315                                 
316                                 /* vertex groups */
317                                 dvert= CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
318                                 
319                                 /* NB: vertex groups here are new version */
320                                 if(dvert) {
321                                         for(i=0; i<me->totvert; i++) {
322                                                 for(j=0; j<dvert[i].totweight; j++) {
323                                                         /*      Find the old vertex group */
324                                                         odg = BLI_findlink(&base->object->defbase, dvert[i].dw[j].def_nr);
325                                                         if(odg) {
326                                                                 /*      Search for a match in the new object, and set new index */
327                                                                 for(dg=ob->defbase.first, index=0; dg; dg=dg->next, index++) {
328                                                                         if(!strcmp(dg->name, odg->name)) {
329                                                                                 dvert[i].dw[j].def_nr = index;
330                                                                                 break;
331                                                                         }
332                                                                 }
333                                                         }
334                                                 }
335                                         }
336                                 }
337                                 
338                                 /* if this is the object we're merging into, no need to do anything */
339                                 if(base->object != ob) {
340                                         /* watch this: switch matmul order really goes wrong */
341                                         mul_m4_m4m4(cmat, base->object->obmat, imat);
342                                         
343                                         /* transform vertex coordinates into new space */
344                                         for(a=0, mv=mvert; a < me->totvert; a++, mv++) {
345                                                 mul_m4_v3(cmat, mv->co);
346                                         }
347                                         
348                                         /* for each shapekey in destination mesh:
349                                          *      - if there's a matching one, copy it across (will need to transform vertices into new space...)
350                                          *      - otherwise, just copy own coordinates of mesh (no need to transform vertex coordinates into new space)
351                                          */
352                                         if(key) {
353                                                 /* if this mesh has any shapekeys, check first, otherwise just copy coordinates */
354                                                 for(kb= key->block.first; kb; kb= kb->next) {
355                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
356                                                         fp1= ((float *)kb->data) + (vertofs*3); 
357                                                         
358                                                         /* check if this mesh has such a shapekey */
359                                                         okb= key_get_named_keyblock(me->key, kb->name);
360                                                         if(okb) {
361                                                                 /* copy this mesh's shapekey to the destination shapekey (need to transform first) */
362                                                                 fp2= ((float *)(okb->data));
363                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
364                                                                         VECCOPY(fp1, fp2);
365                                                                         mul_m4_v3(cmat, fp1);
366                                                                 }
367                                                         }
368                                                         else {
369                                                                 /* copy this mesh's vertex coordinates to the destination shapekey */
370                                                                 mv= mvert;
371                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
372                                                                         VECCOPY(fp1, mv->co);
373                                                                 }
374                                                         }
375                                                 }
376                                         }
377                                 }
378                                 else {
379                                         /* for each shapekey in destination mesh:
380                                          *      - if it was an 'original', copy the appropriate data from nkey
381                                          *      - otherwise, copy across plain coordinates (no need to transform coordinates)
382                                          */
383                                         if(key) {
384                                                 for(kb= key->block.first; kb; kb= kb->next) {
385                                                         /* get pointer to where to write data for this mesh in shapekey's data array */
386                                                         fp1= ((float *)kb->data) + (vertofs*3); 
387                                                         
388                                                         /* check if this was one of the original shapekeys */
389                                                         okb= key_get_named_keyblock(nkey, kb->name);
390                                                         if(okb) {
391                                                                 /* copy this mesh's shapekey to the destination shapekey */
392                                                                 fp2= ((float *)(okb->data));
393                                                                 for(a=0; a < me->totvert; a++, fp1+=3, fp2+=3) {
394                                                                         VECCOPY(fp1, fp2);
395                                                                 }
396                                                         }
397                                                         else {
398                                                                 /* copy base-coordinates to the destination shapekey */
399                                                                 mv= mvert;
400                                                                 for(a=0; a < me->totvert; a++, fp1+=3, mv++) {
401                                                                         VECCOPY(fp1, mv->co);
402                                                                 }
403                                                         }
404                                                 }
405                                         }
406                                 }
407                                 
408                                 /* advance mvert pointer to end of base mesh's data */
409                                 mvert+= me->totvert;
410                         }
411                         
412                         if(me->totface) {
413                                 /* make mapping for materials */
414                                 for(a=1; a<=base->object->totcol; a++) {
415                                         ma= give_current_material(base->object, a);
416
417                                         for(b=0; b<totcol; b++) {
418                                                 if(ma == matar[b]) {
419                                                         matmap[a-1]= b;
420                                                         break;
421                                                 }
422                                         }
423                                 }
424                                 
425                                 CustomData_merge(&me->fdata, &fdata, CD_MASK_MESH, CD_DEFAULT, totface);
426                                 CustomData_copy_data(&me->fdata, &fdata, 0, faceofs, me->totface);
427                                 
428                                 for(a=0; a<me->totface; a++, mface++) {
429                                         mface->v1+= vertofs;
430                                         mface->v2+= vertofs;
431                                         mface->v3+= vertofs;
432                                         if(mface->v4) mface->v4+= vertofs;
433                                         
434                                         if (matmap)
435                                                 mface->mat_nr= matmap[(int)mface->mat_nr];
436                                         else 
437                                                 mface->mat_nr= 0;
438                                 }
439                                 
440                                 faceofs += me->totface;
441                         }
442                         
443                         if(me->totedge) {
444                                 CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
445                                 CustomData_copy_data(&me->edata, &edata, 0, edgeofs, me->totedge);
446                                 
447                                 for(a=0; a<me->totedge; a++, medge++) {
448                                         medge->v1+= vertofs;
449                                         medge->v2+= vertofs;
450                                 }
451                         }
452
453                         if (me->totloop) {
454                                 if(base->object!=ob)
455                                         multiresModifier_prepare_join(scene, base->object, ob);
456                                 
457                                 CustomData_merge(&me->ldata, &ldata, CD_MASK_MESH, CD_DEFAULT, totloop);
458                                 CustomData_copy_data(&me->ldata, &ldata, 0, loopofs, me->totloop);
459                                 
460                                 for(a=0; a<me->totloop; a++, mloop++) {
461                                         mloop->v += vertofs;
462                                         mloop->e += edgeofs;
463                                 }
464                         }
465                         
466                         if(me->totpoly) {
467                                 /* make mapping for materials */
468                                 for(a=1; a<=base->object->totcol; a++) {
469                                         ma= give_current_material(base->object, a);
470
471                                         for(b=0; b<totcol; b++) {
472                                                 if(ma == matar[b]) {
473                                                         matmap[a-1]= b;
474                                                         break;
475                                                 }
476                                         }
477                                 }
478                                 
479                                 CustomData_merge(&me->pdata, &pdata, CD_MASK_MESH, CD_DEFAULT, totpoly);
480                                 CustomData_copy_data(&me->pdata, &pdata, 0, polyofs, me->totpoly);
481                                 
482                                 for(a=0; a<me->totpoly; a++, mpoly++) {
483                                         mpoly->loopstart += loopofs;
484                                         mpoly->mat_nr= matmap ? matmap[(int)mpoly->mat_nr] : 0;
485                                 }
486                                 
487                                 polyofs += me->totpoly;
488                         }
489
490                         /* these are used for relinking (cannot be set earlier, 
491                          * or else reattaching goes wrong)
492                          */
493                         vertofs += me->totvert;
494                         edgeofs += me->totedge;
495                         loopofs += me->totloop;
496                         
497                         /* free base, now that data is merged */
498                         if(base->object != ob)
499                                 ED_base_object_free_and_unlink(bmain, scene, base);
500                 }
501         }
502         CTX_DATA_END;
503         
504         /* return to mesh we're merging to */
505         me= ob->data;
506         
507         CustomData_free(&me->vdata, me->totvert);
508         CustomData_free(&me->edata, me->totedge);
509         CustomData_free(&me->fdata, me->totface);
510         CustomData_free(&me->ldata, me->totloop);
511         CustomData_free(&me->pdata, me->totpoly);
512
513         me->totvert= totvert;
514         me->totedge= totedge;
515         me->totface= totface;
516         me->totloop= totloop;
517         me->totpoly= totpoly;
518         
519         me->vdata= vdata;
520         me->edata= edata;
521         me->fdata= fdata;
522         me->ldata= ldata;
523         me->pdata= pdata;
524
525         mesh_update_customdata_pointers(me);
526         
527         /* old material array */
528         for(a=1; a<=ob->totcol; a++) {
529                 ma= ob->mat[a-1];
530                 if(ma) ma->id.us--;
531         }
532         for(a=1; a<=me->totcol; a++) {
533                 ma= me->mat[a-1];
534                 if(ma) ma->id.us--;
535         }
536         if(ob->mat) MEM_freeN(ob->mat);
537         if(ob->matbits) MEM_freeN(ob->matbits);
538         if(me->mat) MEM_freeN(me->mat);
539         ob->mat= me->mat= NULL;
540         ob->matbits= NULL;
541         
542         if(totcol) {
543                 me->mat= matar;
544                 ob->mat= MEM_callocN(sizeof(void *)*totcol, "join obmatar");
545                 ob->matbits= MEM_callocN(sizeof(char)*totcol, "join obmatbits");
546         }
547         else
548                 MEM_freeN(matar);
549         
550         ob->totcol= me->totcol= totcol;
551         ob->colbits= 0;
552
553         if (matmap) MEM_freeN(matmap);
554         
555         /* other mesh users */
556         test_object_materials((ID *)me);
557         
558         /* free temp copy of destination shapekeys (if applicable) */
559         if(nkey) {
560                 // XXX 2.5 Animato
561 #if 0
562                 /* free it's ipo too - both are not actually freed from memory yet as ID-blocks */
563                 if(nkey->ipo) {
564                         free_ipo(nkey->ipo);
565                         BLI_remlink(&bmain->ipo, nkey->ipo);
566                         MEM_freeN(nkey->ipo);
567                 }
568 #endif
569                 
570                 free_key(nkey);
571                 BLI_remlink(&bmain->key, nkey);
572                 MEM_freeN(nkey);
573         }
574         
575         DAG_scene_sort(bmain, scene);   // removed objects, need to rebuild dag before editmode call
576
577 #if 0
578         ED_object_enter_editmode(C, EM_WAITCURSOR);
579         ED_object_exit_editmode(C, EM_FREEDATA|EM_WAITCURSOR|EM_DO_UNDO);
580 #else
581         /* toggle editmode using lower level functions so this can be called from python */
582         EDBM_MakeEditBMesh(scene->toolsettings, scene, ob);
583         EDBM_LoadEditBMesh(scene, ob);
584         EDBM_FreeEditBMesh(me->edit_btmesh);
585         MEM_freeN(me->edit_btmesh);
586         me->edit_btmesh= NULL;
587         DAG_id_tag_update(&ob->id, OB_RECALC_OB|OB_RECALC_DATA);
588 #endif
589         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
590
591         return OPERATOR_FINISHED;
592 }
593
594 /*********************** JOIN AS SHAPES ***************************/
595
596 /* Append selected meshes vertex locations as shapes of the active mesh, 
597   return 0 if no join is made (error) and 1 of the join is done */
598
599 int join_mesh_shapes_exec(bContext *C, wmOperator *op)
600 {
601         Scene *scene= CTX_data_scene(C);
602         Object *ob= CTX_data_active_object(C);
603         Mesh *me= (Mesh *)ob->data;
604         Mesh *selme=NULL;
605         DerivedMesh *dm=NULL;
606         Key *key=me->key;
607         KeyBlock *kb;
608         int ok=0, nonequal_verts=0;
609         
610         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
611                 if (base->object == ob) continue;
612                 
613                 if (base->object->type==OB_MESH) {
614                         selme = (Mesh *)base->object->data;
615                         
616                         if (selme->totvert==me->totvert)
617                                 ok++;
618                         else
619                                 nonequal_verts=1;
620                 }
621         }
622         CTX_DATA_END;
623         
624         if (!ok) {
625                 if (nonequal_verts)
626                         BKE_report(op->reports, RPT_WARNING, "Selected meshes must have equal numbers of vertices");
627                 else
628                         BKE_report(op->reports, RPT_WARNING, "No additional selected meshes with equal vertex count to join");
629                 return OPERATOR_CANCELLED;
630         }
631         
632         if(key == NULL) {
633                 key= me->key= add_key((ID *)me);
634                 key->type= KEY_RELATIVE;
635
636                 /* first key added, so it was the basis. initialise it with the existing mesh */
637                 kb= add_keyblock(key, NULL);
638                 mesh_to_key(me, kb);
639         }
640         
641         /* now ready to add new keys from selected meshes */
642         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
643                 if (base->object == ob) continue;
644                 
645                 if(base->object->type==OB_MESH) {
646                         selme = (Mesh *)base->object->data;
647                         
648                         if (selme->totvert==me->totvert) {
649                                 dm = mesh_get_derived_deform(scene, base->object, CD_MASK_BAREMESH);
650                                 
651                                 if (!dm) continue;
652                                         
653                                 kb= add_keyblock(key, base->object->id.name+2);
654                                 
655                                 DM_to_meshkey(dm, me, kb);
656                                 
657                                 dm->release(dm);
658                         }
659                 }
660         }
661         CTX_DATA_END;
662         
663         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
664         
665         return OPERATOR_FINISHED;
666 }
667
668 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
669
670 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
671
672 #define MOC_RES                 8
673 #define MOC_NODE_RES    8
674 #define MOC_THRESH              0.00002f
675
676 typedef struct MocNode {
677         struct MocNode *next;
678         intptr_t index[MOC_NODE_RES];
679 } MocNode;
680
681 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
682 {
683         int vx, vy, vz;
684         
685         vx= floor( (co[0]-offs[0])/div[0] );
686         vy= floor( (co[1]-offs[1])/div[1] );
687         vz= floor( (co[2]-offs[2])/div[2] );
688         
689         CLAMP(vx, 0, MOC_RES-1);
690         CLAMP(vy, 0, MOC_RES-1);
691         CLAMP(vz, 0, MOC_RES-1);
692
693         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
694 }
695
696 static void mesh_octree_add_node(MocNode **bt, intptr_t index)
697 {
698         if(*bt==NULL) {
699                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
700                 (*bt)->index[0]= index;
701         }
702         else {
703                 int a;
704                 for(a=0; a<MOC_NODE_RES; a++) {
705                         if((*bt)->index[a]==index)
706                                 return;
707                         else if((*bt)->index[a]==0) {
708                                 (*bt)->index[a]= index;
709                                 return;
710                         }
711                 }
712                 mesh_octree_add_node(&(*bt)->next, index);
713         }
714 }
715
716 static void mesh_octree_free_node(MocNode **bt)
717 {
718         if( (*bt)->next ) {
719                 mesh_octree_free_node(&(*bt)->next);
720         }
721         MEM_freeN(*bt);
722 }
723
724
725 /* temporal define, just to make nicer code below */
726 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
727
728 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, intptr_t index)
729 {
730         float fx, fy, fz;
731         int vx, vy, vz;
732         
733         if (!finite(co[0]) ||
734                 !finite(co[1]) ||
735                 !finite(co[2])
736         ) {
737                 return;
738         }
739         
740         fx= (co[0]-offs[0])/div[0];
741         fy= (co[1]-offs[1])/div[1];
742         fz= (co[2]-offs[2])/div[2];
743         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
744         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
745         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
746         
747         vx= floor(fx);
748         vy= floor(fy);
749         vz= floor(fz);
750         
751         MOC_ADDNODE(vx, vy, vz);
752         
753         if( vx>0 )
754                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
755                         MOC_ADDNODE(vx-1, vy, vz);
756         if( vx<MOC_RES-2 )
757                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
758                         MOC_ADDNODE(vx+1, vy, vz);
759
760         if( vy>0 )
761                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
762                         MOC_ADDNODE(vx, vy-1, vz);
763         if( vy<MOC_RES-2 )
764                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
765                         MOC_ADDNODE(vx, vy+1, vz);
766
767         if( vz>0 )
768                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
769                         MOC_ADDNODE(vx, vy, vz-1);
770         if( vz<MOC_RES-2 )
771                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
772                         MOC_ADDNODE(vx, vy, vz+1);
773         
774 }
775
776 static intptr_t mesh_octree_find_index(MocNode **bt, MVert *mvert, float *co)
777 {
778         float *vec;
779         int a;
780         
781         if(*bt==NULL)
782                 return -1;
783         
784         for(a=0; a<MOC_NODE_RES; a++) {
785                 if((*bt)->index[a]) {
786                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
787                         if(mvert) {
788                                 vec= (mvert+(*bt)->index[a]-1)->co;
789                                 if(compare_v3v3(vec, co, MOC_THRESH))
790                                         return (*bt)->index[a]-1;
791                         }
792                         else {
793                                 BMVert *eve= (BMVert *)((*bt)->index[a]);
794                                 if(compare_v3v3(eve->co, co, MOC_THRESH))
795                                         return (*bt)->index[a];
796                         }
797                 }
798                 else return -1;
799         }
800         if( (*bt)->next)
801                 return mesh_octree_find_index(&(*bt)->next, mvert, co);
802         
803         return -1;
804 }
805
806 static struct {
807         MocNode **table;
808         float offs[3], div[3];
809 } MeshOctree = {NULL, {0, 0, 0}, {0, 0, 0}};
810
811 /* mode is 's' start, or 'e' end, or 'u' use */
812 /* if end, ob can be NULL */
813 intptr_t mesh_octree_table(Object *ob, BMEditMesh *em, float *co, char mode)
814 {
815         MocNode **bt;
816         
817         if(mode=='u') {         /* use table */
818                 if(MeshOctree.table==NULL)
819                         mesh_octree_table(ob, em, NULL, 's');
820            
821                 if(MeshOctree.table) {
822                         Mesh *me= ob->data;
823                         bt= MeshOctree.table + mesh_octree_get_base_offs(co, MeshOctree.offs, MeshOctree.div);
824                         if(em)
825                                 return mesh_octree_find_index(bt, NULL, co);
826                         else
827                                 return mesh_octree_find_index(bt, me->mvert, co);
828                 }
829                 return -1;
830         }
831         else if(mode=='s') {    /* start table */
832                 Mesh *me= ob->data;
833                 float min[3], max[3];
834
835                 /* we compute own bounding box and don't reuse ob->bb because
836                  * we are using the undeformed coordinates*/
837                 INIT_MINMAX(min, max);
838
839                 if(em && me->edit_btmesh==em) {
840                         BMIter iter;
841                         BMVert *eve;
842                         
843                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL)
844                                 DO_MINMAX(eve->co, min, max)
845                 }
846                 else {          
847                         MVert *mvert;
848                         int a;
849                         
850                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
851                                 DO_MINMAX(mvert->co, min, max);
852                 }
853                 
854                 /* for quick unit coordinate calculus */
855                 VECCOPY(MeshOctree.offs, min);
856                 MeshOctree.offs[0]-= MOC_THRESH;                /* we offset it 1 threshold unit extra */
857                 MeshOctree.offs[1]-= MOC_THRESH;
858                 MeshOctree.offs[2]-= MOC_THRESH;
859                 
860                 sub_v3_v3v3(MeshOctree.div, max, min);
861                 MeshOctree.div[0]+= 2*MOC_THRESH;       /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
862                 MeshOctree.div[1]+= 2*MOC_THRESH;
863                 MeshOctree.div[2]+= 2*MOC_THRESH;
864                 
865                 mul_v3_fl(MeshOctree.div, 1.0f/MOC_RES);
866                 if(MeshOctree.div[0]==0.0f) MeshOctree.div[0]= 1.0f;
867                 if(MeshOctree.div[1]==0.0f) MeshOctree.div[1]= 1.0f;
868                 if(MeshOctree.div[2]==0.0f) MeshOctree.div[2]= 1.0f;
869                         
870                 if(MeshOctree.table) /* happens when entering this call without ending it */
871                         mesh_octree_table(ob, em, co, 'e');
872                 
873                 MeshOctree.table= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
874                 
875                 if(em && me->edit_btmesh==em) {
876                         BMVert *eve;
877                         BMIter iter;
878
879                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
880                                 mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
881                         }
882                 }
883                 else {          
884                         MVert *mvert;
885                         int a;
886                         
887                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++)
888                                 mesh_octree_add_nodes(MeshOctree.table, mvert->co, MeshOctree.offs, MeshOctree.div, a+1);
889                 }
890         }
891         else if(mode=='e') { /* end table */
892                 if(MeshOctree.table) {
893                         int a;
894                         
895                         for(a=0, bt=MeshOctree.table; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
896                                 if(*bt) mesh_octree_free_node(bt);
897                         }
898                         MEM_freeN(MeshOctree.table);
899                         MeshOctree.table= NULL;
900                 }
901         }
902         return 0;
903 }
904
905
906 /* ********************* MESH VERTEX MIRR TOPO LOOKUP *************** */
907
908 #define MIRRHASH_TYPE int
909
910 typedef struct MirrTopoPair {
911         long hash;
912         int vIndex;
913 } MirrTopoPair;
914
915 static int MirrTopo_long_sort(const void *l1, const void *l2)
916 {
917         if(                     (MIRRHASH_TYPE)(intptr_t)l1 > (MIRRHASH_TYPE)(intptr_t)l2 ) return  1;
918         else if(        (MIRRHASH_TYPE)(intptr_t)l1 < (MIRRHASH_TYPE)(intptr_t)l2 ) return -1;
919         return 0;
920 }
921
922 static int MirrTopo_item_sort(const void *v1, const void *v2)
923 {
924         if(                     ((MirrTopoPair *)v1)->hash > ((MirrTopoPair *)v2)->hash ) return  1;
925         else if(        ((MirrTopoPair *)v1)->hash < ((MirrTopoPair *)v2)->hash ) return -1;
926         return 0;
927 }
928
929 static long *mesh_topo_lookup = NULL;
930 static int  mesh_topo_lookup_tot = -1;
931 static int  mesh_topo_lookup_mode = -1;
932
933 /* mode is 's' start, or 'e' end, or 'u' use */
934 /* if end, ob can be NULL */
935 long mesh_mirrtopo_table(Object *ob, char mode)
936 {
937         if(mode=='u') {         /* use table */
938                 Mesh *me= ob->data;
939                 if(     (mesh_topo_lookup==NULL) ||
940                         (mesh_topo_lookup_mode != ob->mode) ||
941                         (me->edit_btmesh && me->edit_btmesh->bm->totvert != mesh_topo_lookup_tot) ||
942                         (me->edit_btmesh==NULL && me->totvert != mesh_topo_lookup_tot)
943                 ) {
944                         mesh_mirrtopo_table(ob, 's');
945                 }
946         } else if(mode=='s') { /* start table */
947                 Mesh *me= ob->data;
948                 MEdge *medge;
949                 BMEditMesh *em= me->edit_btmesh;
950                 BMEdge *eed;
951                 BMIter iter;
952                 MIRRHASH_TYPE *MirrTopoHash = NULL;
953                 MIRRHASH_TYPE *MirrTopoHash_Prev = NULL;
954                 MirrTopoPair *MirrTopoPairs;
955                 int a, last, totvert;
956                 int totUnique= -1, totUniqueOld= -1;
957
958                 mesh_topo_lookup_mode= ob->mode;
959
960                 /* reallocate if needed */
961                 if (mesh_topo_lookup) {
962                         MEM_freeN(mesh_topo_lookup);
963                         mesh_topo_lookup = NULL;
964                 }
965
966                 if(em) {
967                         BMVert *eve;
968
969                         totvert= 0;
970                         BM_ITER(eve, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
971                                 BM_SetIndex(eve, totvert);
972                                 totvert++;
973                         }
974                 }
975                 else {
976                         totvert = me->totvert;
977                 }
978
979                 MirrTopoHash = MEM_callocN( totvert * sizeof(MIRRHASH_TYPE), "TopoMirr" );
980
981                 /* Initialize the vert-edge-user counts used to detect unique topology */
982                 if(em) {
983                         BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
984                                 MirrTopoHash[BM_GetIndex(eed->v1)]++;
985                                 MirrTopoHash[BM_GetIndex(eed->v2)]++;
986                         }
987                 } else {
988                         for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
989                                 MirrTopoHash[medge->v1]++;
990                                 MirrTopoHash[medge->v2]++;
991                         }
992                 }
993
994                 MirrTopoHash_Prev = MEM_dupallocN( MirrTopoHash );
995
996                 totUniqueOld = -1;
997                 while(1) {
998                         /* use the number of edges per vert to give verts unique topology IDs */
999
1000                         if(em) {
1001                                 BM_ITER(eed, &iter, em->bm, BM_EDGES_OF_MESH, NULL) {
1002                                         MirrTopoHash[BM_GetIndex(eed->v1)] += MirrTopoHash_Prev[BM_GetIndex(eed->v2)];
1003                                         MirrTopoHash[BM_GetIndex(eed->v2)] += MirrTopoHash_Prev[BM_GetIndex(eed->v1)];
1004                                 }
1005                         } else {
1006                                 for(a=0, medge=me->medge; a<me->totedge; a++, medge++) {
1007                                         /* This can make really big numbers, wrapping around here is fine */
1008                                         MirrTopoHash[medge->v1] += MirrTopoHash_Prev[medge->v2];
1009                                         MirrTopoHash[medge->v2] += MirrTopoHash_Prev[medge->v1];
1010                                 }
1011                         }
1012                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1013
1014                         /* sort so we can count unique values */
1015                         qsort(MirrTopoHash_Prev, totvert, sizeof(MIRRHASH_TYPE), MirrTopo_long_sort);
1016
1017                         totUnique = 1; /* account for skiping the first value */
1018                         for(a=1; a<totvert; a++) {
1019                                 if (MirrTopoHash_Prev[a-1] != MirrTopoHash_Prev[a]) {
1020                                         totUnique++;
1021                                 }
1022                         }
1023
1024                         if (totUnique <= totUniqueOld) {
1025                                 /* Finish searching for unique valus when 1 loop dosnt give a
1026                                  * higher number of unique values compared to the previous loop */
1027                                 break;
1028                         } else {
1029                                 totUniqueOld = totUnique;
1030                         }
1031                         /* Copy the hash calculated this iter, so we can use them next time */
1032                         memcpy(MirrTopoHash_Prev, MirrTopoHash, sizeof(MIRRHASH_TYPE) * totvert);
1033                 }
1034
1035                 /* Hash/Index pairs are needed for sorting to find index pairs */
1036                 MirrTopoPairs= MEM_callocN( sizeof(MirrTopoPair) * totvert, "MirrTopoPairs");
1037
1038                 /* since we are looping through verts, initialize these values here too */
1039                 mesh_topo_lookup = MEM_mallocN( totvert * sizeof(long), "mesh_topo_lookup" );
1040
1041                 if(em) {
1042                         EDBM_init_index_arrays(em,1,0,0);
1043                 }
1044
1045
1046                 for(a=0; a<totvert; a++) {
1047                         MirrTopoPairs[a].hash= MirrTopoHash[a];
1048                         MirrTopoPairs[a].vIndex = a;
1049
1050                         /* initialize lookup */
1051                         mesh_topo_lookup[a] = -1;
1052                 }
1053
1054                 qsort(MirrTopoPairs, totvert, sizeof(MirrTopoPair), MirrTopo_item_sort);
1055
1056                 /* Since the loop starts at 2, we must define the last index where the hash's differ */
1057                 last = ((totvert >= 2) && (MirrTopoPairs[0].hash == MirrTopoPairs[1].hash)) ? 0 : 1;
1058
1059                 /* Get the pairs out of the sorted hashes, note, totvert+1 means we can use the previous 2,
1060                  * but you cant ever access the last 'a' index of MirrTopoPairs */
1061                 for(a=2; a < totvert+1; a++) {
1062                         /* printf("I %d %ld %d\n", (a-last), MirrTopoPairs[a  ].hash, MirrTopoPairs[a  ].vIndex ); */
1063                         if ((a==totvert) || (MirrTopoPairs[a-1].hash != MirrTopoPairs[a].hash)) {
1064                                 if (a-last==2) {
1065                                         if(em) {
1066                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   (long)EDBM_get_vert_for_index(em, MirrTopoPairs[a-2].vIndex);
1067                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   (long)EDBM_get_vert_for_index(em, MirrTopoPairs[a-1].vIndex);
1068                                         } else {
1069                                                 mesh_topo_lookup[MirrTopoPairs[a-1].vIndex] =   MirrTopoPairs[a-2].vIndex;
1070                                                 mesh_topo_lookup[MirrTopoPairs[a-2].vIndex] =   MirrTopoPairs[a-1].vIndex;
1071                                         }
1072                                 }
1073                                 last= a;
1074                         }
1075                 }
1076                 if(em) {
1077                         EDBM_free_index_arrays(em);
1078                 }
1079
1080                 MEM_freeN( MirrTopoPairs );
1081                 MirrTopoPairs = NULL;
1082
1083                 MEM_freeN( MirrTopoHash );
1084                 MEM_freeN( MirrTopoHash_Prev );
1085
1086                 mesh_topo_lookup_tot = totvert;
1087
1088         } else if(mode=='e') { /* end table */
1089                 if (mesh_topo_lookup) {
1090                         MEM_freeN(mesh_topo_lookup);
1091                 }
1092                 mesh_topo_lookup = NULL;
1093                 mesh_topo_lookup_tot= -1;
1094         }
1095         return 0;
1096 }
1097
1098 static int mesh_get_x_mirror_vert_spacial(Object *ob, int index)
1099 {
1100         Mesh *me= ob->data;
1101         MVert *mvert;
1102         float vec[3];
1103         
1104         mvert= me->mvert+index;
1105         vec[0]= -mvert->co[0];
1106         vec[1]= mvert->co[1];
1107         vec[2]= mvert->co[2];
1108         
1109         return mesh_octree_table(ob, NULL, vec, 'u');
1110 }
1111
1112 static int mesh_get_x_mirror_vert_topo(Object *ob, int index)
1113 {
1114         if (mesh_mirrtopo_table(ob, 'u')==-1)
1115                 return -1;
1116
1117         return mesh_topo_lookup[index];
1118 }
1119
1120 int mesh_get_x_mirror_vert(Object *ob, int index)
1121 {
1122         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1123                 return mesh_get_x_mirror_vert_topo(ob, index);
1124         } else {
1125                 return mesh_get_x_mirror_vert_spacial(ob, index);
1126         }
1127         return 0;
1128 }
1129
1130 static BMVert *editbmesh_get_x_mirror_vert_spacial(Object *ob, BMEditMesh *em, float *co)
1131 {
1132         float vec[3];
1133         intptr_t poinval;
1134         
1135         /* ignore nan verts */
1136         if (!finite(co[0]) ||
1137                 !finite(co[1]) ||
1138                 !finite(co[2])
1139            )
1140                 return NULL;
1141         
1142         vec[0]= -co[0];
1143         vec[1]= co[1];
1144         vec[2]= co[2];
1145         
1146         poinval= mesh_octree_table(ob, em, vec, 'u');
1147         if(poinval != -1)
1148                 return (BMVert *)(poinval);
1149         return NULL;
1150 }
1151
1152 static BMVert *editbmesh_get_x_mirror_vert_topo(Object *ob, struct BMEditMesh *em, BMVert *eve, int index)
1153 {
1154         long poinval;
1155         if (mesh_mirrtopo_table(ob, 'u')==-1)
1156                 return NULL;
1157
1158         if (index == -1) {
1159                 BMIter iter;
1160                 BMVert *v;
1161                 
1162                 index = 0;
1163                 BM_ITER(v, &iter, em->bm, BM_VERTS_OF_MESH, NULL) {
1164                         if (v == eve)
1165                                 break;
1166                         index++;
1167                 }
1168                 
1169                 if (index == em->bm->totvert) {
1170                         return NULL;
1171                 }
1172         }
1173
1174         poinval= mesh_topo_lookup[ index ];
1175
1176         if(poinval != -1)
1177                 return (BMVert *)(poinval);
1178         return NULL;
1179 }       
1180
1181 BMVert *editbmesh_get_x_mirror_vert(Object *ob, struct BMEditMesh *em, BMVert *eve, float *co, int index)
1182 {
1183         //BMESH_TODO use this flag, ME_EDIT_MIRROR_TOPO, at appropriate places
1184         if (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_TOPO) {
1185                 return editbmesh_get_x_mirror_vert_topo(ob, em, eve, index);
1186         } else {
1187                 return editbmesh_get_x_mirror_vert_spacial(ob, em, co);
1188         }
1189 }
1190
1191
1192
1193 static float *editmesh_get_mirror_uv(BMEditMesh *em, int axis, float *uv, float *mirrCent, float *face_cent)
1194 {
1195         float vec[2];
1196         float cent_vec[2];
1197         float cent[2];
1198
1199         /* ignore nan verts */
1200         if (isnan(uv[0]) || !finite(uv[0]) ||
1201                 isnan(uv[1]) || !finite(uv[1])
1202            )
1203                 return NULL;
1204
1205         if (axis) {
1206                 vec[0]= uv[0];
1207                 vec[1]= -((uv[1])-mirrCent[1]) + mirrCent[1];
1208
1209                 cent_vec[0] = face_cent[0];
1210                 cent_vec[1]= -((face_cent[1])-mirrCent[1]) + mirrCent[1];
1211         } else {
1212                 vec[0]= -((uv[0])-mirrCent[0]) + mirrCent[0];
1213                 vec[1]= uv[1];
1214
1215                 cent_vec[0]= -((face_cent[0])-mirrCent[0]) + mirrCent[0];
1216                 cent_vec[1] = face_cent[1];
1217         }
1218
1219         /* TODO - Optimize */
1220         {
1221                 BMIter iter;
1222                 BMFace *efa;
1223                 
1224                 BM_ITER(efa, &iter, em->bm, BM_FACES_OF_MESH, NULL) {
1225                         poly_uv_center(em, efa, cent);
1226                         
1227                         if ( (fabs(cent[0] - cent_vec[0]) < 0.001) && (fabs(cent[1] - cent_vec[1]) < 0.001) ) {
1228                                 BMIter liter;
1229                                 BMLoop *l;
1230                                 
1231                                 BM_ITER(l, &liter, em->bm, BM_LOOPS_OF_FACE, efa) {
1232                                         MLoopUV *luv = CustomData_bmesh_get(&em->bm->ldata, l->head.data, CD_MLOOPUV);
1233                                         if ( (fabs(luv->uv[0] - vec[0]) < 0.001) && (fabs(luv->uv[1] - vec[1]) < 0.001) ) {
1234                                                 return luv->uv;
1235                                                                 
1236                                 }
1237                         }
1238                 }
1239         }
1240         }
1241
1242         return NULL;
1243 }
1244
1245 static unsigned int mirror_facehash(const void *ptr)
1246 {
1247         const MFace *mf= ptr;
1248         int v0, v1;
1249
1250         if(mf->v4) {
1251                 v0= MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
1252                 v1= MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
1253         }
1254         else {
1255                 v0= MIN3(mf->v1, mf->v2, mf->v3);
1256                 v1= MAX3(mf->v1, mf->v2, mf->v3);
1257         }
1258
1259         return ((v0*39)^(v1*31));
1260 }
1261
1262 static int mirror_facerotation(MFace *a, MFace *b)
1263 {
1264         if(b->v4) {
1265                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3 && a->v4==b->v4)
1266                         return 0;
1267                 else if(a->v4==b->v1 && a->v1==b->v2 && a->v2==b->v3 && a->v3==b->v4)
1268                         return 1;
1269                 else if(a->v3==b->v1 && a->v4==b->v2 && a->v1==b->v3 && a->v2==b->v4)
1270                         return 2;
1271                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v4==b->v3 && a->v1==b->v4)
1272                         return 3;
1273         }
1274         else {
1275                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3)
1276                         return 0;
1277                 else if(a->v3==b->v1 && a->v1==b->v2 && a->v2==b->v3)
1278                         return 1;
1279                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v1==b->v3)
1280                         return 2;
1281         }
1282         
1283         return -1;
1284 }
1285
1286 static int mirror_facecmp(const void *a, const void *b)
1287 {
1288         return (mirror_facerotation((MFace*)a, (MFace*)b) == -1);
1289 }
1290
1291 int *mesh_get_x_mirror_faces(Object *ob, BMEditMesh *em)
1292 {
1293         Mesh *me= ob->data;
1294         MVert *mv, *mvert= me->mvert;
1295         MFace mirrormf, *mf, *hashmf, *mface= me->mface;
1296         GHash *fhash;
1297         int *mirrorverts, *mirrorfaces;
1298         int a;
1299
1300         mirrorverts= MEM_callocN(sizeof(int)*me->totvert, "MirrorVerts");
1301         mirrorfaces= MEM_callocN(sizeof(int)*2*me->totface, "MirrorFaces");
1302
1303         mesh_octree_table(ob, em, NULL, 's');
1304
1305         for(a=0, mv=mvert; a<me->totvert; a++, mv++)
1306                 mirrorverts[a]= mesh_get_x_mirror_vert(ob, a);
1307
1308         mesh_octree_table(ob, em, NULL, 'e');
1309
1310         fhash= BLI_ghash_new(mirror_facehash, mirror_facecmp, "mirror_facehash gh");
1311         for(a=0, mf=mface; a<me->totface; a++, mf++)
1312                 BLI_ghash_insert(fhash, mf, mf);
1313
1314         for(a=0, mf=mface; a<me->totface; a++, mf++) {
1315                 mirrormf.v1= mirrorverts[mf->v3];
1316                 mirrormf.v2= mirrorverts[mf->v2];
1317                 mirrormf.v3= mirrorverts[mf->v1];
1318                 mirrormf.v4= (mf->v4)? mirrorverts[mf->v4]: 0;
1319
1320                 /* make sure v4 is not 0 if a quad */
1321                 if(mf->v4 && mirrormf.v4==0) {
1322                         SWAP(int, mirrormf.v1, mirrormf.v3);
1323                         SWAP(int, mirrormf.v2, mirrormf.v4);
1324                 }
1325
1326                 hashmf= BLI_ghash_lookup(fhash, &mirrormf);
1327                 if(hashmf) {
1328                         mirrorfaces[a*2]= hashmf - mface;
1329                         mirrorfaces[a*2+1]= mirror_facerotation(&mirrormf, hashmf);
1330                 }
1331                 else
1332                         mirrorfaces[a*2]= -1;
1333         }
1334
1335         BLI_ghash_free(fhash, NULL, NULL);
1336         MEM_freeN(mirrorverts);
1337         
1338         return mirrorfaces;
1339 }