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