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