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