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