2.5
[blender.git] / source / blender / editors / mesh / meshtools.c
1 /**
2  * $Id: 
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2004 by Blender Foundation
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /*
31         meshtools.c: no editmode (violated already :), tools operating on meshes
32 */
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <math.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_image_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_material_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_space_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_world_types.h"
50
51 #include "BLI_arithb.h"
52 #include "BLI_blenlib.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_blender.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_customdata.h"
62 #include "BKE_global.h"
63 #include "BKE_image.h"
64 #include "BKE_library.h"
65 #include "BKE_main.h"
66 #include "BKE_mesh.h"
67 #include "BKE_material.h"
68 #include "BKE_object.h"
69 #include "BKE_utildefines.h"
70
71 #include "RE_pipeline.h"
72 #include "RE_shader_ext.h"
73
74 #include "PIL_time.h"
75
76 #include "IMB_imbuf_types.h"
77 #include "IMB_imbuf.h"
78
79 #include "GPU_draw.h"
80
81 #include "BLO_sys_types.h" // for intptr_t support
82
83 #include "ED_mesh.h"
84 #include "ED_object.h"
85 #include "ED_view3d.h"
86
87 /* own include */
88 #include "mesh_intern.h"
89
90
91 /* from rendercode.c */
92 #define VECMUL(dest, f)                  dest[0]*= f; dest[1]*= f; dest[2]*= f
93
94 /* XXX */
95 static void BIF_undo_push() {}
96 static void waitcursor() {}
97 static void error() {}
98 static int pupmenu() {return 0;}
99 /* XXX */
100
101
102 /* * ********************** no editmode!!! *********** */
103
104 /* join selected meshes into the active mesh, context sensitive
105 return 0 if no join is made (error) and 1 of the join is done */
106 int join_mesh(Scene *scene, View3D *v3d)
107 {
108         Base *base, *nextb;
109         Object *ob;
110         Material **matar, *ma;
111         Mesh *me;
112         MVert *mvert, *mvertmain;
113         MEdge *medge = NULL, *medgemain;
114         MFace *mface = NULL, *mfacemain;
115         float imat[4][4], cmat[4][4];
116         int a, b, totcol, totedge=0, totvert=0, totface=0, ok=0, vertofs, map[MAXMAT];
117         int     i, j, index, haskey=0, hasmulti=0, edgeofs, faceofs;
118         bDeformGroup *dg, *odg;
119         MDeformVert *dvert;
120         CustomData vdata, edata, fdata;
121
122         if(scene->obedit) return 0;
123         
124         ob= OBACT;
125         if(!ob || ob->type!=OB_MESH) return 0;
126         
127         if (object_data_is_libdata(ob)) {
128 // XXX          error_libdata();
129                 return 0;
130         }
131
132         /* count & check */
133         base= FIRSTBASE;
134         while(base) {
135                 if(TESTBASELIB_BGMODE(base)) { /* BGMODE since python can access */
136                         if(base->object->type==OB_MESH) {
137                                 me= base->object->data;
138                                 totvert+= me->totvert;
139                                 totface+= me->totface;
140
141                                 if(base->object == ob) ok= 1;
142
143                                 if(me->key) {
144                                         haskey= 1;
145                                         break;
146                                 }
147                                 if(me->mr) {
148                                         hasmulti= 1;
149                                         break;
150                                 }
151                         }
152                 }
153                 base= base->next;
154         }
155         
156         if(haskey) {
157                 error("Can't join meshes with vertex keys");
158                 return 0;
159         }
160         if(hasmulti) {
161                 error("Can't join meshes with Multires");
162                 return 0;
163         }
164         /* that way the active object is always selected */ 
165         if(ok==0) return 0;
166         
167         if(totvert==0 || totvert>MESH_MAX_VERTS) return 0;
168
169         /* if needed add edges to other meshes */
170         for(base= FIRSTBASE; base; base= base->next) {
171                 if(TESTBASELIB_BGMODE(base)) {
172                         if(base->object->type==OB_MESH) {
173                                 me= base->object->data;
174                                 totedge += me->totedge;
175                         }
176                 }
177         }
178         
179         /* new material indices and material array */
180         matar= MEM_callocN(sizeof(void *)*MAXMAT, "join_mesh");
181         totcol= ob->totcol;
182         
183         /* obact materials in new main array, is nicer start! */
184         for(a=1; a<=ob->totcol; a++) {
185                 matar[a-1]= give_current_material(ob, a);
186                 id_us_plus((ID *)matar[a-1]);
187                 /* increase id->us : will be lowered later */
188         }
189         
190         base= FIRSTBASE;
191         while(base) {
192                 if(TESTBASELIB_BGMODE(base)) {
193                         if(ob!=base->object && base->object->type==OB_MESH) {
194                                 me= base->object->data;
195
196                                 // Join this object's vertex groups to the base one's
197                                 for (dg=base->object->defbase.first; dg; dg=dg->next){
198                                         /* See if this group exists in the object */
199                                         for (odg=ob->defbase.first; odg; odg=odg->next){
200                                                 if (!strcmp(odg->name, dg->name)){
201                                                         break;
202                                                 }
203                                         }
204                                         if (!odg){
205                                                 odg = MEM_callocN (sizeof(bDeformGroup), "join deformGroup");
206                                                 memcpy (odg, dg, sizeof(bDeformGroup));
207                                                 BLI_addtail(&ob->defbase, odg);
208                                         }
209
210                                 }
211                                 if (ob->defbase.first && ob->actdef==0)
212                                         ob->actdef=1;
213
214                                 if(me->totvert) {
215                                         for(a=1; a<=base->object->totcol; a++) {
216                                                 ma= give_current_material(base->object, a);
217                                                 if(ma) {
218                                                         for(b=0; b<totcol; b++) {
219                                                                 if(ma == matar[b]) break;
220                                                         }
221                                                         if(b==totcol) {
222                                                                 matar[b]= ma;
223                                                                 ma->id.us++;
224                                                                 totcol++;
225                                                         }
226                                                         if(totcol>=MAXMAT-1) break;
227                                                 }
228                                         }
229                                 }
230                         }
231                         if(totcol>=MAXMAT-1) break;
232                 }
233                 base= base->next;
234         }
235
236         me= ob->data;
237
238         memset(&vdata, 0, sizeof(vdata));
239         memset(&edata, 0, sizeof(edata));
240         memset(&fdata, 0, sizeof(fdata));
241         
242         mvert= CustomData_add_layer(&vdata, CD_MVERT, CD_CALLOC, NULL, totvert);
243         medge= CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge);
244         mface= CustomData_add_layer(&fdata, CD_MFACE, CD_CALLOC, NULL, totface);
245
246         mvertmain= mvert;
247         medgemain= medge;
248         mfacemain= mface;
249
250         /* inverse transorm all selected meshes in this object */
251         Mat4Invert(imat, ob->obmat);
252
253         vertofs= 0;
254         edgeofs= 0;
255         faceofs= 0;
256         base= FIRSTBASE;
257         while(base) {
258                 nextb= base->next;
259                 if (TESTBASELIB_BGMODE(base)) {
260                         if(base->object->type==OB_MESH) {
261                                 
262                                 me= base->object->data;
263                                 
264                                 if(me->totvert) {
265                                         CustomData_merge(&me->vdata, &vdata, CD_MASK_MESH, CD_DEFAULT, totvert);
266                                         CustomData_copy_data(&me->vdata, &vdata, 0, vertofs, me->totvert);
267                                         
268                                         dvert= CustomData_get(&vdata, vertofs, CD_MDEFORMVERT);
269
270                                         /* NEW VERSION */
271                                         if (dvert){
272                                                 for (i=0; i<me->totvert; i++){
273                                                         for (j=0; j<dvert[i].totweight; j++){
274                                                                 //      Find the old vertex group
275                                                                 odg = BLI_findlink (&base->object->defbase, dvert[i].dw[j].def_nr);
276                                                                 if(odg) {
277                                                                         //      Search for a match in the new object
278                                                                         for (dg=ob->defbase.first, index=0; dg; dg=dg->next, index++){
279                                                                                 if (!strcmp(dg->name, odg->name)){
280                                                                                         dvert[i].dw[j].def_nr = index;
281                                                                                         break;
282                                                                                 }
283                                                                         }
284                                                                 }
285                                                         }
286                                                 }
287                                         }
288
289                                         if(base->object != ob) {
290                                                 /* watch this: switch matmul order really goes wrong */
291                                                 Mat4MulMat4(cmat, base->object->obmat, imat);
292                                                 
293                                                 a= me->totvert;
294                                                 while(a--) {
295                                                         Mat4MulVecfl(cmat, mvert->co);
296                                                         mvert++;
297                                                 }
298                                         }
299                                         else mvert+= me->totvert;
300                                 }
301                                 if(me->totface) {
302                                 
303                                         /* make mapping for materials */
304                                         memset(map, 0, 4*MAXMAT);
305                                         for(a=1; a<=base->object->totcol; a++) {
306                                                 ma= give_current_material(base->object, a);
307                                                 if(ma) {
308                                                         for(b=0; b<totcol; b++) {
309                                                                 if(ma == matar[b]) {
310                                                                         map[a-1]= b;
311                                                                         break;
312                                                                 }
313                                                         }
314                                                 }
315                                         }
316
317                                         CustomData_merge(&me->fdata, &fdata, CD_MASK_MESH, CD_DEFAULT, totface);
318                                         CustomData_copy_data(&me->fdata, &fdata, 0, faceofs, me->totface);
319
320                                         for(a=0; a<me->totface; a++, mface++) {
321                                                 mface->v1+= vertofs;
322                                                 mface->v2+= vertofs;
323                                                 mface->v3+= vertofs;
324                                                 if(mface->v4) mface->v4+= vertofs;
325                                                 
326                                                 mface->mat_nr= map[(int)mface->mat_nr];
327                                         }
328
329                                         faceofs += me->totface;
330                                 }
331                                 
332                                 if(me->totedge) {
333                                         CustomData_merge(&me->edata, &edata, CD_MASK_MESH, CD_DEFAULT, totedge);
334                                         CustomData_copy_data(&me->edata, &edata, 0, edgeofs, me->totedge);
335
336                                         for(a=0; a<me->totedge; a++, medge++) {
337                                                 medge->v1+= vertofs;
338                                                 medge->v2+= vertofs;
339                                         }
340
341                                         edgeofs += me->totedge;
342                                 }
343                                 
344                                 vertofs += me->totvert;
345                                 
346                                 if(base->object!=ob)
347                                         ED_base_object_free_and_unlink(scene, base);
348                         }
349                 }
350                 base= nextb;
351         }
352         
353         me= ob->data;
354         
355         CustomData_free(&me->vdata, me->totvert);
356         CustomData_free(&me->edata, me->totedge);
357         CustomData_free(&me->fdata, me->totface);
358
359         me->totvert= totvert;
360         me->totedge= totedge;
361         me->totface= totface;
362         
363         me->vdata= vdata;
364         me->edata= edata;
365         me->fdata= fdata;
366
367         mesh_update_customdata_pointers(me);
368         
369         /* old material array */
370         for(a=1; a<=ob->totcol; a++) {
371                 ma= ob->mat[a-1];
372                 if(ma) ma->id.us--;
373         }
374         for(a=1; a<=me->totcol; a++) {
375                 ma= me->mat[a-1];
376                 if(ma) ma->id.us--;
377         }
378         if(ob->mat) MEM_freeN(ob->mat);
379         if(me->mat) MEM_freeN(me->mat);
380         ob->mat= me->mat= 0;
381         
382         if(totcol) {
383                 me->mat= matar;
384                 ob->mat= MEM_callocN(sizeof(void *)*totcol, "join obmatar");
385         }
386         else MEM_freeN(matar);
387         
388         ob->totcol= me->totcol= totcol;
389         ob->colbits= 0;
390         
391         /* other mesh users */
392         test_object_materials((ID *)me);
393         
394         DAG_scene_sort(scene);  // removed objects, need to rebuild dag before editmode call
395         
396 // XXX  enter_editmode(EM_WAITCURSOR);
397 //      exit_editmode(EM_FREEDATA|EM_WAITCURSOR);       // freedata, but no undo
398         
399         BIF_undo_push("Join Mesh");
400         return 1;
401 }
402
403
404 /* ********************** SORT FACES ******************* */
405
406 static void permutate(void *list, int num, int size, int *index)
407 {
408         void *buf;
409         int len;
410         int i;
411
412         len = num * size;
413
414         buf = MEM_mallocN(len, "permutate");
415         memcpy(buf, list, len);
416         
417         for (i = 0; i < num; i++) {
418                 memcpy((char *)list + (i * size), (char *)buf + (index[i] * size), size);
419         }
420         MEM_freeN(buf);
421 }
422
423 /* sort faces on view axis */
424 static float *face_sort_floats;
425 static int float_sort(const void *v1, const void *v2)
426 {
427         float x1, x2;
428         
429         x1 = face_sort_floats[((int *) v1)[0]];
430         x2 = face_sort_floats[((int *) v2)[0]];
431         
432         if( x1 > x2 ) return 1;
433         else if( x1 < x2 ) return -1;
434         return 0;
435 }
436
437
438 void sort_faces(Scene *scene, View3D *v3d)
439 {
440         Object *ob= OBACT;
441         Mesh *me;
442         CustomDataLayer *layer;
443         int i, *index;
444         short event;
445         float reverse = 1;
446         int ctrl= 0;    // XXX
447         
448         if(!ob) return;
449         if(scene->obedit) return;
450         if(ob->type!=OB_MESH) return;
451         if (!v3d) return;
452         
453         me= ob->data;
454         if(me->totface==0) return;
455         
456         event = pupmenu(
457         "Sort Faces (Ctrl to reverse)%t|"
458         "View Axis%x1|"
459         "Cursor Distance%x2|"
460         "Material%x3|"
461         "Selection%x4|"
462         "Randomize%x5");
463         
464         if (event==-1) return;
465         
466         if(ctrl)
467                 reverse = -1;
468         
469 /*      create index list */
470         index = (int *) MEM_mallocN(sizeof(int) * me->totface, "sort faces");
471         for (i = 0; i < me->totface; i++) {
472                 index[i] = i;
473         }
474         
475         face_sort_floats = (float *) MEM_mallocN(sizeof(float) * me->totface, "sort faces float");
476         
477 /* sort index list instead of faces itself 
478    and apply this permutation to all face layers */
479    
480         if (event == 5) {
481                 /* Random */
482                 for(i=0; i<me->totface; i++) {
483                         face_sort_floats[i] = BLI_frand();
484                 }
485                 qsort(index, me->totface, sizeof(int), float_sort);             
486         } else {
487                 MFace *mf;
488                 float vec[3];
489                 float mat[4][4];
490                 float cur[3];
491                 
492                 if (event == 1)
493                         Mat4MulMat4(mat, OBACT->obmat, v3d->viewmat); /* apply the view matrix to the object matrix */
494                 else if (event == 2) { /* sort from cursor */
495                         if( v3d && v3d->localview ) {
496                                 VECCOPY(cur, v3d->cursor);
497                         } else {
498                                 VECCOPY(cur, scene->cursor);
499                         }
500                         Mat4Invert(mat, OBACT->obmat);
501                         Mat4MulVecfl(mat, cur);
502                 }
503                 
504                 mf= me->mface;
505                 for(i=0; i<me->totface; i++, mf++) {
506                         
507                         if (event==3) {
508                                 face_sort_floats[i] = ((float)mf->mat_nr)*reverse;
509                         } else if (event==4) {
510                                 /*selected first*/
511                                 if (mf->flag & ME_FACE_SEL)     face_sort_floats[i] = 0.0;
512                                 else                                            face_sort_floats[i] = reverse;
513                         } else {
514                                 /* find the faces center */
515                                 VECADD(vec, (me->mvert+mf->v1)->co, (me->mvert+mf->v2)->co);
516                                 if (mf->v4) {
517                                         VECADD(vec, vec, (me->mvert+mf->v3)->co);
518                                         VECADD(vec, vec, (me->mvert+mf->v4)->co);
519                                         VECMUL(vec, 0.25f);
520                                 } else {
521                                         VECADD(vec, vec, (me->mvert+mf->v3)->co);
522                                         VECMUL(vec, 1.0f/3.0f);
523                                 } /* done */
524                                 
525                                 if (event == 1) { /* sort on view axis */
526                                         Mat4MulVecfl(mat, vec);
527                                         face_sort_floats[i] = vec[2] * reverse;
528                                 } else { /* distance from cursor*/
529                                         face_sort_floats[i] = VecLenf(cur, vec) * reverse; /* back to front */
530                                 }
531                         }
532                 }
533                 qsort(index, me->totface, sizeof(int), float_sort);
534         }
535         
536         MEM_freeN(face_sort_floats);
537         
538         for(i = 0; i < me->fdata.totlayer; i++) {
539                 layer = &me->fdata.layers[i];
540                 permutate(layer->data, me->totface, CustomData_sizeof(layer->type), index);
541         }
542
543         MEM_freeN(index);
544
545         DAG_object_flush_update(scene, ob, OB_RECALC_DATA);
546 }
547
548
549
550 /* ********************* MESH VERTEX OCTREE LOOKUP ************* */
551
552 /* important note; this is unfinished, needs better API for editmode, and custom threshold */
553
554 #define MOC_RES                 8
555 #define MOC_NODE_RES    8
556 #define MOC_THRESH              0.0002f
557
558 typedef struct MocNode {
559         struct MocNode *next;
560         intptr_t index[MOC_NODE_RES];
561 } MocNode;
562
563 static int mesh_octree_get_base_offs(float *co, float *offs, float *div)
564 {
565         int vx, vy, vz;
566         
567         vx= floor( (co[0]-offs[0])/div[0] );
568         vy= floor( (co[1]-offs[1])/div[1] );
569         vz= floor( (co[2]-offs[2])/div[2] );
570         
571         CLAMP(vx, 0, MOC_RES-1);
572         CLAMP(vy, 0, MOC_RES-1);
573         CLAMP(vz, 0, MOC_RES-1);
574
575         return (vx*MOC_RES*MOC_RES) + vy*MOC_RES + vz;
576 }
577
578 static void mesh_octree_add_node(MocNode **bt, intptr_t index)
579 {
580         if(*bt==NULL) {
581                 *bt= MEM_callocN(sizeof(MocNode), "MocNode");
582                 (*bt)->index[0]= index;
583         }
584         else {
585                 int a;
586                 for(a=0; a<MOC_NODE_RES; a++) {
587                         if((*bt)->index[a]==index)
588                                 return;
589                         else if((*bt)->index[a]==0) {
590                                 (*bt)->index[a]= index;
591                                 return;
592                         }
593                 }
594                 mesh_octree_add_node(&(*bt)->next, index);
595         }
596 }
597
598 static void mesh_octree_free_node(MocNode **bt)
599 {
600         if( (*bt)->next ) {
601                 mesh_octree_free_node(&(*bt)->next);
602         }
603         MEM_freeN(*bt);
604 }
605
606
607 /* temporal define, just to make nicer code below */
608 #define MOC_ADDNODE(vx, vy, vz) mesh_octree_add_node(basetable + ((vx)*MOC_RES*MOC_RES) + (vy)*MOC_RES + (vz), index)
609
610 static void mesh_octree_add_nodes(MocNode **basetable, float *co, float *offs, float *div, intptr_t index)
611 {
612         float fx, fy, fz;
613         int vx, vy, vz;
614         
615         if (isnan(co[0]) || !finite(co[0]) ||
616                 isnan(co[1]) || !finite(co[1]) ||
617                 isnan(co[2]) || !finite(co[2])
618         ) {
619                 return;
620         }
621         
622         fx= (co[0]-offs[0])/div[0];
623         fy= (co[1]-offs[1])/div[1];
624         fz= (co[2]-offs[2])/div[2];
625         CLAMP(fx, 0.0f, MOC_RES-MOC_THRESH);
626         CLAMP(fy, 0.0f, MOC_RES-MOC_THRESH);
627         CLAMP(fz, 0.0f, MOC_RES-MOC_THRESH);
628         
629         vx= floor(fx);
630         vy= floor(fy);
631         vz= floor(fz);
632         
633         MOC_ADDNODE(vx, vy, vz);
634         
635         if( vx>0 )
636                 if( fx-((float)vx)-MOC_THRESH < 0.0f)
637                         MOC_ADDNODE(vx-1, vy, vz);
638         if( vx<MOC_RES-2 )
639                 if( fx-((float)vx)+MOC_THRESH > 1.0f)
640                         MOC_ADDNODE(vx+1, vy, vz);
641
642         if( vy>0 )
643                 if( fy-((float)vy)-MOC_THRESH < 0.0f) 
644                         MOC_ADDNODE(vx, vy-1, vz);
645         if( vy<MOC_RES-2 )
646                 if( fy-((float)vy)+MOC_THRESH > 1.0f) 
647                         MOC_ADDNODE(vx, vy+1, vz);
648
649         if( vz>0 )
650                 if( fz-((float)vz)-MOC_THRESH < 0.0f) 
651                         MOC_ADDNODE(vx, vy, vz-1);
652         if( vz<MOC_RES-2 )
653                 if( fz-((float)vz)+MOC_THRESH > 1.0f) 
654                         MOC_ADDNODE(vx, vy, vz+1);
655         
656 }
657
658 static intptr_t mesh_octree_find_index(MocNode **bt, float (*orco)[3], MVert *mvert, float *co)
659 {
660         float *vec;
661         int a;
662         
663         if(*bt==NULL)
664                 return -1;
665         
666         for(a=0; a<MOC_NODE_RES; a++) {
667                 if((*bt)->index[a]) {
668                         /* does mesh verts and editmode, code looks potential dangerous, octree should really be filled OK! */
669                         if(orco) {
670                                 vec= orco[(*bt)->index[a]-1];
671                                 if(FloatCompare(vec, co, MOC_THRESH))
672                                         return (*bt)->index[a]-1;
673                         }
674                         else if(mvert) {
675                                 vec= (mvert+(*bt)->index[a]-1)->co;
676                                 if(FloatCompare(vec, co, MOC_THRESH))
677                                         return (*bt)->index[a]-1;
678                         }
679                         else {
680                                 EditVert *eve= (EditVert *)((*bt)->index[a]);
681                                 if(FloatCompare(eve->co, co, MOC_THRESH))
682                                         return (*bt)->index[a];
683                         }
684                 }
685                 else return -1;
686         }
687         if( (*bt)->next)
688                 return mesh_octree_find_index(&(*bt)->next, orco, mvert, co);
689         
690         return -1;
691 }
692
693 static struct {
694         MocNode **table;
695         float offs[3], div[3];
696         float (*orco)[3];
697         float orcoloc[3];
698 } MeshOctree = {NULL, {0, 0, 0}, {0, 0, 0}, NULL};
699
700 /* mode is 's' start, or 'e' end, or 'u' use */
701 /* if end, ob can be NULL */
702 intptr_t mesh_octree_table(Object *ob, EditMesh *em, float *co, char mode)
703 {
704         MocNode **bt;
705         
706         if(mode=='u') {         /* use table */
707                 if(MeshOctree.table==NULL)
708                         mesh_octree_table(ob, em, NULL, 's');
709            
710                 if(MeshOctree.table) {
711                         Mesh *me= ob->data;
712                         bt= MeshOctree.table + mesh_octree_get_base_offs(co, MeshOctree.offs, MeshOctree.div);
713                         if(me->edit_mesh)
714                                 return mesh_octree_find_index(bt, NULL, NULL, co);
715                         else
716                                 return mesh_octree_find_index(bt, MeshOctree.orco, me->mvert, co);
717                 }
718                 return -1;
719         }
720         else if(mode=='s') {    /* start table */
721                 Mesh *me= ob->data;
722                 float min[3], max[3];
723
724                 /* we compute own bounding box and don't reuse ob->bb because
725                  * we are using the undeformed coordinates*/
726                 INIT_MINMAX(min, max);
727
728                 if(me->edit_mesh==em) {
729                         EditVert *eve;
730                         
731                         for(eve= em->verts.first; eve; eve= eve->next)
732                                 DO_MINMAX(eve->co, min, max)
733                 }
734                 else {          
735                         MVert *mvert;
736                         float *vco;
737                         int a, totvert;
738                         
739                         MeshOctree.orco= mesh_getRefKeyCos(me, &totvert);
740                         mesh_get_texspace(me, MeshOctree.orcoloc, NULL, NULL);
741                         
742                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++) {
743                                 vco= (MeshOctree.orco)? MeshOctree.orco[a]: mvert->co;
744                                 DO_MINMAX(vco, min, max);
745                         }
746                 }
747                 
748                 /* for quick unit coordinate calculus */
749                 VECCOPY(MeshOctree.offs, min);
750                 MeshOctree.offs[0]-= MOC_THRESH;                /* we offset it 1 threshold unit extra */
751                 MeshOctree.offs[1]-= MOC_THRESH;
752                 MeshOctree.offs[2]-= MOC_THRESH;
753                 
754                 VecSubf(MeshOctree.div, max, min);
755                 MeshOctree.div[0]+= 2*MOC_THRESH;       /* and divide with 2 threshold unit more extra (try 8x8 unit grid on paint) */
756                 MeshOctree.div[1]+= 2*MOC_THRESH;
757                 MeshOctree.div[2]+= 2*MOC_THRESH;
758                 
759                 VecMulf(MeshOctree.div, 1.0f/MOC_RES);
760                 if(MeshOctree.div[0]==0.0f) MeshOctree.div[0]= 1.0f;
761                 if(MeshOctree.div[1]==0.0f) MeshOctree.div[1]= 1.0f;
762                 if(MeshOctree.div[2]==0.0f) MeshOctree.div[2]= 1.0f;
763                         
764                 if(MeshOctree.table) /* happens when entering this call without ending it */
765                         mesh_octree_table(ob, em, co, 'e');
766                 
767                 MeshOctree.table= MEM_callocN(MOC_RES*MOC_RES*MOC_RES*sizeof(void *), "sym table");
768                 
769                 if(me->edit_mesh==em) {
770                         EditVert *eve;
771
772                         for(eve= em->verts.first; eve; eve= eve->next) {
773                                 mesh_octree_add_nodes(MeshOctree.table, eve->co, MeshOctree.offs, MeshOctree.div, (intptr_t)(eve));
774                         }
775                 }
776                 else {          
777                         MVert *mvert;
778                         float *vco;
779                         int a;
780                         
781                         for(a=0, mvert= me->mvert; a<me->totvert; a++, mvert++) {
782                                 vco= (MeshOctree.orco)? MeshOctree.orco[a]: mvert->co;
783                                 mesh_octree_add_nodes(MeshOctree.table, vco, MeshOctree.offs, MeshOctree.div, a+1);
784                         }
785                 }
786         }
787         else if(mode=='e') { /* end table */
788                 if(MeshOctree.table) {
789                         int a;
790                         
791                         for(a=0, bt=MeshOctree.table; a<MOC_RES*MOC_RES*MOC_RES; a++, bt++) {
792                                 if(*bt) mesh_octree_free_node(bt);
793                         }
794                         MEM_freeN(MeshOctree.table);
795                         MeshOctree.table= NULL;
796                 }
797                 if(MeshOctree.orco) {
798                         MEM_freeN(MeshOctree.orco);
799                         MeshOctree.orco= NULL;
800                 }
801         }
802         return 0;
803 }
804
805 int mesh_get_x_mirror_vert(Object *ob, int index)
806 {
807         Mesh *me= ob->data;
808         MVert *mvert;
809         float vec[3];
810         
811         if(MeshOctree.orco) {
812                 float *loc= MeshOctree.orcoloc;
813
814                 vec[0]= -(MeshOctree.orco[index][0] + loc[0]) - loc[0];
815                 vec[1]= MeshOctree.orco[index][1];
816                 vec[2]= MeshOctree.orco[index][2];
817         }
818         else {
819                 mvert= me->mvert+index;
820                 vec[0]= -mvert->co[0];
821                 vec[1]= mvert->co[1];
822                 vec[2]= mvert->co[2];
823         }
824         
825         return mesh_octree_table(ob, NULL, vec, 'u');
826 }
827
828 EditVert *editmesh_get_x_mirror_vert(Object *ob, EditMesh *em, float *co)
829 {
830         float vec[3];
831         intptr_t poinval;
832         
833         /* ignore nan verts */
834         if (isnan(co[0]) || !finite(co[0]) ||
835                 isnan(co[1]) || !finite(co[1]) ||
836                 isnan(co[2]) || !finite(co[2])
837            )
838                 return NULL;
839         
840         vec[0]= -co[0];
841         vec[1]= co[1];
842         vec[2]= co[2];
843         
844         poinval= mesh_octree_table(ob, em, vec, 'u');
845         if(poinval != -1)
846                 return (EditVert *)(poinval);
847         return NULL;
848 }
849
850 static unsigned int mirror_facehash(void *ptr)
851 {
852         MFace *mf= ptr;
853         int v0, v1;
854
855         if(mf->v4) {
856                 v0= MIN4(mf->v1, mf->v2, mf->v3, mf->v4);
857                 v1= MAX4(mf->v1, mf->v2, mf->v3, mf->v4);
858         }
859         else {
860                 v0= MIN3(mf->v1, mf->v2, mf->v3);
861                 v1= MAX3(mf->v1, mf->v2, mf->v3);
862         }
863
864         return ((v0*39)^(v1*31));
865 }
866
867 static int mirror_facerotation(MFace *a, MFace *b)
868 {
869         if(b->v4) {
870                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3 && a->v4==b->v4)
871                         return 0;
872                 else if(a->v4==b->v1 && a->v1==b->v2 && a->v2==b->v3 && a->v3==b->v4)
873                         return 1;
874                 else if(a->v3==b->v1 && a->v4==b->v2 && a->v1==b->v3 && a->v2==b->v4)
875                         return 2;
876                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v4==b->v3 && a->v1==b->v4)
877                         return 3;
878         }
879         else {
880                 if(a->v1==b->v1 && a->v2==b->v2 && a->v3==b->v3)
881                         return 0;
882                 else if(a->v3==b->v1 && a->v1==b->v2 && a->v2==b->v3)
883                         return 1;
884                 else if(a->v2==b->v1 && a->v3==b->v2 && a->v1==b->v3)
885                         return 2;
886         }
887         
888         return -1;
889 }
890
891 static int mirror_facecmp(void *a, void *b)
892 {
893         return (mirror_facerotation((MFace*)a, (MFace*)b) == -1);
894 }
895
896 int *mesh_get_x_mirror_faces(Object *ob, EditMesh *em)
897 {
898         Mesh *me= ob->data;
899         MVert *mv, *mvert= me->mvert;
900         MFace mirrormf, *mf, *hashmf, *mface= me->mface;
901         GHash *fhash;
902         int *mirrorverts, *mirrorfaces;
903         int a;
904
905         mirrorverts= MEM_callocN(sizeof(int)*me->totvert, "MirrorVerts");
906         mirrorfaces= MEM_callocN(sizeof(int)*2*me->totface, "MirrorFaces");
907
908         mesh_octree_table(ob, em, NULL, 's');
909
910         for(a=0, mv=mvert; a<me->totvert; a++, mv++)
911                 mirrorverts[a]= mesh_get_x_mirror_vert(ob, a);
912
913         mesh_octree_table(ob, em, NULL, 'e');
914
915         fhash= BLI_ghash_new(mirror_facehash, mirror_facecmp);
916         for(a=0, mf=mface; a<me->totface; a++, mf++)
917                 BLI_ghash_insert(fhash, mf, mf);
918
919         for(a=0, mf=mface; a<me->totface; a++, mf++) {
920                 mirrormf.v1= mirrorverts[mf->v3];
921                 mirrormf.v2= mirrorverts[mf->v2];
922                 mirrormf.v3= mirrorverts[mf->v1];
923                 mirrormf.v4= (mf->v4)? mirrorverts[mf->v4]: 0;
924
925                 /* make sure v4 is not 0 if a quad */
926                 if(mf->v4 && mirrormf.v4==0) {
927                         SWAP(int, mirrormf.v1, mirrormf.v3);
928                         SWAP(int, mirrormf.v2, mirrormf.v4);
929                 }
930
931                 hashmf= BLI_ghash_lookup(fhash, &mirrormf);
932                 if(hashmf) {
933                         mirrorfaces[a*2]= hashmf - mface;
934                         mirrorfaces[a*2+1]= mirror_facerotation(&mirrormf, hashmf);
935                 }
936                 else
937                         mirrorfaces[a*2]= -1;
938         }
939
940         BLI_ghash_free(fhash, NULL, NULL);
941         MEM_freeN(mirrorverts);
942         
943         return mirrorfaces;
944 }
945
946 /* ****************** render BAKING ********************** */
947
948 /* threaded break test */
949 static int thread_break(void)
950 {
951         return G.afbreek;
952 }
953
954 static ScrArea *biggest_image_area(bScreen *screen)
955 {
956         ScrArea *sa, *big= NULL;
957         int size, maxsize= 0;
958         
959         for(sa= screen->areabase.first; sa; sa= sa->next) {
960                 if(sa->spacetype==SPACE_IMAGE) {
961                         size= sa->winx*sa->winy;
962                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
963                                 maxsize= size;
964                                 big= sa;
965                         }
966                 }
967         }
968         return big;
969 }
970
971
972 typedef struct BakeRender {
973         Render *re;
974         struct Object *actob;
975         int event, tot, ready;
976 } BakeRender;
977
978 static void *do_bake_render(void *bake_v)
979 {
980         BakeRender *bkr= bake_v;
981         
982         bkr->tot= RE_bake_shade_all_selected(bkr->re, bkr->event, bkr->actob);
983         bkr->ready= 1;
984         
985         return NULL;
986 }
987
988
989 void objects_bake_render(Scene *scene, short event, char **error_msg)
990 {
991         Object *actob= OBACT;
992         int active= scene->r.bake_flag & R_BAKE_TO_ACTIVE;
993         short prev_r_raytrace= 0, prev_wo_amb_occ= 0;
994         
995         if(event==0) event= scene->r.bake_mode;
996         
997         if(scene->r.renderer!=R_INTERN) {        
998                 *error_msg = "Bake only supported for Internal Renderer";
999                 return;
1000         }        
1001         
1002         if(active && !actob) {
1003                 *error_msg = "No active object";
1004                 return;
1005         }
1006         
1007         if(event>0) {
1008                 bScreen *screen= NULL; // XXX CTX
1009                 Render *re= RE_NewRender("_Bake View_");
1010                 ScrArea *area= biggest_image_area(screen);
1011                 ListBase threads;
1012                 BakeRender bkr;
1013                 int timer=0, tot; // XXX, sculptmode= G.f & G_SCULPTMODE;
1014
1015 // XXX          if(sculptmode) set_sculptmode();
1016                 
1017                 if(event==1) event= RE_BAKE_ALL;
1018                 else if(event==2) event= RE_BAKE_AO;
1019                 else if(event==3) event= RE_BAKE_NORMALS;
1020                 else if(event==4) event= RE_BAKE_TEXTURE;
1021                 else if(event==5) event= RE_BAKE_DISPLACEMENT;
1022                 else event= RE_BAKE_SHADOW;
1023
1024                 if(event==RE_BAKE_AO) {
1025                         if(scene->world==NULL) {
1026                                 *error_msg = "No world set up";
1027                                 return;
1028                         }
1029
1030                         /* If raytracing or AO is disabled, switch it on temporarily for baking. */
1031                         prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
1032                         scene->world->mode |= WO_AMB_OCC;
1033                 }
1034                 if(event==RE_BAKE_AO || active) {
1035                         prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
1036                         scene->r.mode |= R_RAYTRACE;
1037                 }
1038                 
1039                 waitcursor(1);
1040                 RE_test_break_cb(re, thread_break);
1041                 G.afbreek= 0;   /* blender_test_break uses this global */
1042                 
1043                 RE_Database_Baking(re, scene, event, (active)? actob: NULL);
1044                 
1045                 /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
1046         
1047                 BLI_init_threads(&threads, do_bake_render, 1);
1048                 bkr.re= re;
1049                 bkr.event= event;
1050                 bkr.ready= 0;
1051                 bkr.actob= (active)? actob: NULL;
1052                 BLI_insert_thread(&threads, &bkr);
1053                 
1054                 while(bkr.ready==0) {
1055                         PIL_sleep_ms(50);
1056                         if(bkr.ready)
1057                                 break;
1058                         
1059                         if (!G.background) {
1060                                 blender_test_break();
1061                                 
1062                                 timer++;
1063                                 if(area && timer==20) {
1064                                         Image *ima= RE_bake_shade_get_image();
1065                                         if(ima) ((SpaceImage *)area->spacedata.first)->image= ima;
1066 // XX                                   scrarea_do_windraw(area);
1067 //                                      myswapbuffers();        
1068                                         timer= 0;
1069                                 }
1070                         }
1071                 }
1072                 BLI_end_threads(&threads);
1073                 tot= bkr.tot;
1074                 
1075                 RE_Database_Free(re);
1076                 waitcursor(0);
1077                 
1078                 if(tot==0) *error_msg = "No Images found to bake to";
1079                 else {
1080                         Image *ima;
1081                         /* force OpenGL reload and mipmap recalc */
1082                         for(ima= G.main->image.first; ima; ima= ima->id.next) {
1083                                 if(ima->ok==IMA_OK_LOADED) {
1084                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1085                                         if(ibuf && (ibuf->userflags & IB_BITMAPDIRTY)) {
1086                                                 GPU_free_image(ima); 
1087                                                 imb_freemipmapImBuf(ibuf);
1088                                         }
1089                                 }
1090                         }
1091                 }
1092                 
1093                 /* restore raytrace and AO */
1094                 if(event==RE_BAKE_AO)
1095                         if(prev_wo_amb_occ == 0)
1096                                 scene->world->mode &= ~WO_AMB_OCC;
1097
1098                 if(event==RE_BAKE_AO || active)
1099                         if(prev_r_raytrace == 0)
1100                                 scene->r.mode &= ~R_RAYTRACE;
1101                 
1102 // XXX          if(sculptmode) set_sculptmode();
1103                 
1104         }
1105 }
1106
1107 /* all selected meshes with UV maps are rendered for current scene visibility */
1108 static void objects_bake_render_ui(Scene *scene, short event)
1109 {
1110         char *error_msg = NULL;
1111 //      int is_editmode = (obedit!=NULL);
1112         
1113         /* Deal with editmode, this is a bit clunky but since UV's are in editmode, users are likely to bake from their */
1114 // XXX  if (is_editmode) exit_editmode(0);
1115         
1116         objects_bake_render(scene, event, &error_msg);
1117         
1118 // XXX  if (is_editmode) enter_editmode(0);
1119         
1120         if (error_msg)
1121                 error(error_msg);
1122 }
1123
1124 void objects_bake_render_menu(Scene *scene)
1125 {
1126         short event;
1127         
1128         event= pupmenu("Bake Selected Meshes %t|Full Render %x1|Ambient Occlusion %x2|Normals %x3|Texture Only %x4|Displacement %x5|Shadow %x6");
1129         if (event < 1) return;
1130         objects_bake_render_ui(scene, event);
1131 }
1132