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