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