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