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