use path remapping for all make local functions, patch from Alex Fraser with changes.
[blender.git] / source / blender / blenkernel / intern / mball.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Jiri Hnidek <jiri.hnidek@vslib.cz>.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * MetaBalls are created from a single Object (with a name without number in it),
26  * here the DispList and BoundBox also is located.
27  * All objects with the same name (but with a number in it) are added to this.
28  *
29  * texture coordinates are patched within the displist
30  */
31
32 /** \file blender/blenkernel/intern/mball.c
33  *  \ingroup bke
34  */
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <math.h>
39 #include <stdlib.h>
40 #include <ctype.h>
41 #include <float.h>
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_material_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_meta_types.h"
47 #include "DNA_scene_types.h"
48
49
50 #include "BLI_blenlib.h"
51 #include "BLI_math.h"
52 #include "BLI_utildefines.h"
53 #include "BLI_bpath.h"
54
55
56 #include "BKE_global.h"
57 #include "BKE_main.h"
58
59 /*  #include "BKE_object.h" */
60 #include "BKE_animsys.h"
61 #include "BKE_scene.h"
62 #include "BKE_library.h"
63 #include "BKE_displist.h"
64 #include "BKE_mball.h"
65 #include "BKE_object.h"
66 #include "BKE_material.h"
67
68 /* Global variables */
69
70 static float thresh= 0.6f;
71 static int totelem=0;
72 static MetaElem **mainb;
73 static octal_tree *metaball_tree = NULL;
74 /* Functions */
75
76 void unlink_mball(MetaBall *mb)
77 {
78         int a;
79         
80         for(a=0; a<mb->totcol; a++) {
81                 if(mb->mat[a]) mb->mat[a]->id.us--;
82                 mb->mat[a]= NULL;
83         }
84 }
85
86
87 /* do not free mball itself */
88 void free_mball(MetaBall *mb)
89 {
90         unlink_mball(mb);       
91         
92         if(mb->adt) {
93                 BKE_free_animdata((ID *)mb);
94                 mb->adt = NULL;
95         }
96         if(mb->mat) MEM_freeN(mb->mat);
97         if(mb->bb) MEM_freeN(mb->bb);
98         BLI_freelistN(&mb->elems);
99         if(mb->disp.first) freedisplist(&mb->disp);
100 }
101
102 MetaBall *add_mball(const char *name)
103 {
104         MetaBall *mb;
105         
106         mb= alloc_libblock(&G.main->mball, ID_MB, name);
107         
108         mb->size[0]= mb->size[1]= mb->size[2]= 1.0;
109         mb->texflag= MB_AUTOSPACE;
110         
111         mb->wiresize= 0.4f;
112         mb->rendersize= 0.2f;
113         mb->thresh= 0.6f;
114         
115         return mb;
116 }
117
118 MetaBall *copy_mball(MetaBall *mb)
119 {
120         MetaBall *mbn;
121         int a;
122         
123         mbn= copy_libblock(mb);
124
125         BLI_duplicatelist(&mbn->elems, &mb->elems);
126         
127         mbn->mat= MEM_dupallocN(mb->mat);
128         for(a=0; a<mbn->totcol; a++) {
129                 id_us_plus((ID *)mbn->mat[a]);
130         }
131         mbn->bb= MEM_dupallocN(mb->bb);
132
133         mbn->editelems= NULL;
134         mbn->lastelem= NULL;
135         
136         return mbn;
137 }
138
139 static void extern_local_mball(MetaBall *mb)
140 {
141         if(mb->mat) {
142                 extern_local_matarar(mb->mat, mb->totcol);
143         }
144 }
145
146 void make_local_mball(MetaBall *mb)
147 {
148         Main *bmain= G.main;
149         Object *ob;
150         int is_local= FALSE, is_lib= FALSE;
151
152         /* - only lib users: do nothing
153          * - only local users: set flag
154          * - mixed: make copy
155          */
156         
157         if(mb->id.lib==NULL) return;
158         if(mb->id.us==1) {
159                 id_clear_lib_data(bmain, &mb->id);
160                 extern_local_mball(mb);
161                 
162                 return;
163         }
164
165         for(ob= G.main->object.first; ob && ELEM(0, is_lib, is_local); ob= ob->id.next) {
166                 if(ob->data == mb) {
167                         if(ob->id.lib) is_lib= TRUE;
168                         else is_local= TRUE;
169                 }
170         }
171         
172         if(is_local && is_lib == FALSE) {
173                 id_clear_lib_data(bmain, &mb->id);
174                 extern_local_mball(mb);
175         }
176         else if(is_local && is_lib) {
177                 char *bpath_user_data[2]= {bmain->name, mb->id.lib->filepath};
178                 MetaBall *mbn= copy_mball(mb);
179                 mbn->id.us= 0;
180
181                 /* Remap paths of new ID using old library as base. */
182                 bpath_traverse_id(bmain, &mbn->id, bpath_relocate_visitor, 0, bpath_user_data);
183
184                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
185                         if(ob->data == mb) {
186                                 if(ob->id.lib==NULL) {
187                                         ob->data= mbn;
188                                         mbn->id.us++;
189                                         mb->id.us--;
190                                 }
191                         }
192                 }
193         }
194 }
195
196 /* most simple meta-element adding function
197  * don't do context manipulation here (rna uses) */
198 MetaElem *add_metaball_element(MetaBall *mb, const int type)
199 {
200         MetaElem *ml= MEM_callocN(sizeof(MetaElem), "metaelem");
201
202         unit_qt(ml->quat);
203
204         ml->rad= 2.0;
205         ml->s= 2.0;
206         ml->flag= MB_SCALE_RAD;
207
208         switch(type) {
209         case MB_BALL:
210                 ml->type = MB_BALL;
211                 ml->expx= ml->expy= ml->expz= 1.0;
212
213                 break;
214         case MB_TUBE:
215                 ml->type = MB_TUBE;
216                 ml->expx= ml->expy= ml->expz= 1.0;
217
218                 break;
219         case MB_PLANE:
220                 ml->type = MB_PLANE;
221                 ml->expx= ml->expy= ml->expz= 1.0;
222
223                 break;
224         case MB_ELIPSOID:
225                 ml->type = MB_ELIPSOID;
226                 ml->expx= 1.2f;
227                 ml->expy= 0.8f;
228                 ml->expz= 1.0;
229                 
230                 break;
231         case MB_CUBE:
232                 ml->type = MB_CUBE;
233                 ml->expx= ml->expy= ml->expz= 1.0;
234
235                 break;
236         default:
237                 break;
238         }
239
240         BLI_addtail(&mb->elems, ml);
241
242         return ml;
243 }
244 /** Compute bounding box of all MetaElems/MetaBalls.
245  *
246  * Bounding box is computed from polygonized surface. Object *ob is
247  * basic MetaBall (usually with name Meta). All other MetaBalls (with
248  * names Meta.001, Meta.002, etc) are included in this Bounding Box.
249  */
250 void tex_space_mball(Object *ob)
251 {
252         DispList *dl;
253         BoundBox *bb;
254         float *data, min[3], max[3] /*, loc[3], size[3] */;
255         int tot, doit=0;
256
257         if(ob->bb==NULL) ob->bb= MEM_callocN(sizeof(BoundBox), "mb boundbox");
258         bb= ob->bb;
259         
260         /* Weird one, this. */
261 /*      INIT_MINMAX(min, max); */
262         (min)[0]= (min)[1]= (min)[2]= 1.0e30f;
263         (max)[0]= (max)[1]= (max)[2]= -1.0e30f;
264
265         dl= ob->disp.first;
266         while(dl) {
267                 tot= dl->nr;
268                 if(tot) doit= 1;
269                 data= dl->verts;
270                 while(tot--) {
271                         /* Also weird... but longer. From utildefines. */
272                         DO_MINMAX(data, min, max);
273                         data+= 3;
274                 }
275                 dl= dl->next;
276         }
277
278         if(!doit) {
279                 min[0] = min[1] = min[2] = -1.0f;
280                 max[0] = max[1] = max[2] = 1.0f;
281         }
282         /*
283         loc[0]= (min[0]+max[0])/2.0f;
284         loc[1]= (min[1]+max[1])/2.0f;
285         loc[2]= (min[2]+max[2])/2.0f;
286         
287         size[0]= (max[0]-min[0])/2.0f;
288         size[1]= (max[1]-min[1])/2.0f;
289         size[2]= (max[2]-min[2])/2.0f;
290         */
291         boundbox_set_from_min_max(bb, min, max);
292 }
293
294 float *make_orco_mball(Object *ob, ListBase *dispbase)
295 {
296         BoundBox *bb;
297         DispList *dl;
298         float *data, *orco, *orcodata;
299         float loc[3], size[3];
300         int a;
301
302         /* restore size and loc */
303         bb= ob->bb;
304         loc[0]= (bb->vec[0][0]+bb->vec[4][0])/2.0f;
305         size[0]= bb->vec[4][0]-loc[0];
306         loc[1]= (bb->vec[0][1]+bb->vec[2][1])/2.0f;
307         size[1]= bb->vec[2][1]-loc[1];
308         loc[2]= (bb->vec[0][2]+bb->vec[1][2])/2.0f;
309         size[2]= bb->vec[1][2]-loc[2];
310
311         dl= dispbase->first;
312         orcodata= MEM_mallocN(sizeof(float)*3*dl->nr, "MballOrco");
313
314         data= dl->verts;
315         orco= orcodata;
316         a= dl->nr;
317         while(a--) {
318                 orco[0]= (data[0]-loc[0])/size[0];
319                 orco[1]= (data[1]-loc[1])/size[1];
320                 orco[2]= (data[2]-loc[2])/size[2];
321
322                 data+= 3;
323                 orco+= 3;
324         }
325
326         return orcodata;
327 }
328
329 /* Note on mball basis stuff 2.5x (this is a can of worms)
330  * This really needs a rewrite/refactor its totally broken in anything other then basic cases
331  * Multiple Scenes + Set Scenes & mixing mball basis SHOULD work but fails to update the depsgraph on rename
332  * and linking into scenes or removal of basis mball. so take care when changing this code.
333  * 
334  * Main idiot thing here is that the system returns find_basis_mball() objects which fail a is_basis_mball() test.
335  *
336  * Not only that but the depsgraph and their areas depend on this behavior!, so making small fixes here isn't worth it.
337  * - Campbell
338  */
339
340
341 /** \brief Test, if Object *ob is basic MetaBall.
342  *
343  * It test last character of Object ID name. If last character
344  * is digit it return 0, else it return 1.
345  */
346 int is_basis_mball(Object *ob)
347 {
348         int len;
349         
350         /* just a quick test */
351         len= strlen(ob->id.name);
352         if( isdigit(ob->id.name[len-1]) ) return 0;
353         return 1;
354 }
355
356 /* return nonzero if ob1 is a basis mball for ob */
357 int is_mball_basis_for(Object *ob1, Object *ob2)
358 {
359         int basis1nr, basis2nr;
360         char basis1name[32], basis2name[32];
361
362         BLI_split_name_num(basis1name, &basis1nr, ob1->id.name+2, '.');
363         BLI_split_name_num(basis2name, &basis2nr, ob2->id.name+2, '.');
364
365         if(!strcmp(basis1name, basis2name)) return is_basis_mball(ob1);
366         else return 0;
367 }
368
369 /* \brief copy some properties from object to other metaball object with same base name
370  *
371  * When some properties (wiresize, threshold, update flags) of metaball are changed, then this properties
372  * are copied to all metaballs in same "group" (metaballs with same base name: MBall,
373  * MBall.001, MBall.002, etc). The most important is to copy properties to the base metaball,
374  * because this metaball influence polygonisation of metaballs. */
375 void copy_mball_properties(Scene *scene, Object *active_object)
376 {
377         Scene *sce_iter= scene;
378         Base *base;
379         Object *ob;
380         MetaBall *active_mball = (MetaBall*)active_object->data;
381         int basisnr, obnr;
382         char basisname[32], obname[32];
383         
384         BLI_split_name_num(basisname, &basisnr, active_object->id.name+2, '.');
385
386         /* XXX recursion check, see scene.c, just too simple code this next_object() */
387         if(F_ERROR==next_object(&sce_iter, 0, NULL, NULL))
388                 return;
389         
390         while(next_object(&sce_iter, 1, &base, &ob)) {
391                 if (ob->type==OB_MBALL) {
392                         if(ob!=active_object){
393                                 BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
394
395                                 /* Object ob has to be in same "group" ... it means, that it has to have
396                                  * same base of its name */
397                                 if(strcmp(obname, basisname)==0){
398                                         MetaBall *mb= ob->data;
399
400                                         /* Copy properties from selected/edited metaball */
401                                         mb->wiresize= active_mball->wiresize;
402                                         mb->rendersize= active_mball->rendersize;
403                                         mb->thresh= active_mball->thresh;
404                                         mb->flag= active_mball->flag;
405                                 }
406                         }
407                 }
408         }
409 }
410
411 /** \brief This function finds basic MetaBall.
412  *
413  * Basic MetaBall doesn't include any number at the end of
414  * its name. All MetaBalls with same base of name can be
415  * blended. MetaBalls with different basic name can't be
416  * blended.
417  *
418  * warning!, is_basis_mball() can fail on returned object, see long note above.
419  */
420 Object *find_basis_mball(Scene *scene, Object *basis)
421 {
422         Scene *sce_iter= scene;
423         Base *base;
424         Object *ob,*bob= basis;
425         MetaElem *ml=NULL;
426         int basisnr, obnr;
427         char basisname[32], obname[32];
428
429         BLI_split_name_num(basisname, &basisnr, basis->id.name+2, '.');
430         totelem= 0;
431
432         /* XXX recursion check, see scene.c, just too simple code this next_object() */
433         if(F_ERROR==next_object(&sce_iter, 0, NULL, NULL))
434                 return NULL;
435         
436         while(next_object(&sce_iter, 1, &base, &ob)) {
437                 
438                 if (ob->type==OB_MBALL) {
439                         if(ob==bob){
440                                 MetaBall *mb= ob->data;
441                                 
442                                 /* if bob object is in edit mode, then dynamic list of all MetaElems
443                                  * is stored in editelems */
444                                 if(mb->editelems) ml= mb->editelems->first;
445                                 /* if bob object is in object mode */
446                                 else ml= mb->elems.first;
447                         }
448                         else{
449                                 BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
450
451                                 /* object ob has to be in same "group" ... it means, that it has to have
452                                  * same base of its name */
453                                 if(strcmp(obname, basisname)==0){
454                                         MetaBall *mb= ob->data;
455                                         
456                                         /* if object is in edit mode, then dynamic list of all MetaElems
457                                          * is stored in editelems */
458                                         if(mb->editelems) ml= mb->editelems->first;
459                                         /* if bob object is in object mode */
460                                         else ml= mb->elems.first;
461                                         
462                                         if(obnr<basisnr){
463                                                 if(!(ob->flag & OB_FROMDUPLI)){
464                                                         basis= ob;
465                                                         basisnr= obnr;
466                                                 }
467                                         }       
468                                 }
469                         }
470                         
471                         while(ml){
472                                 if(!(ml->flag & MB_HIDE)) totelem++;
473                                 ml= ml->next;
474                         }
475                 }
476         }
477
478         return basis;
479 }
480
481
482 /* ******************** ARITH ************************* */
483
484 /* BASED AT CODE (but mostly rewritten) :
485  * C code from the article
486  * "An Implicit Surface Polygonizer"
487  * by Jules Bloomenthal, jbloom@beauty.gmu.edu
488  * in "Graphics Gems IV", Academic Press, 1994
489
490  * Authored by Jules Bloomenthal, Xerox PARC.
491  * Copyright (c) Xerox Corporation, 1991.  All rights reserved.
492  * Permission is granted to reproduce, use and distribute this code for
493  * any and all purposes, provided that this notice appears in all copies. */
494
495 #define RES     12 /* # converge iterations    */
496
497 #define L       0  /* left direction:   -x, -i */
498 #define R       1  /* right direction:  +x, +i */
499 #define B       2  /* bottom direction: -y, -j */
500 #define T       3  /* top direction:    +y, +j */
501 #define N       4  /* near direction:   -z, -k */
502 #define F       5  /* far direction:    +z, +k */
503 #define LBN     0  /* left bottom near corner  */
504 #define LBF     1  /* left bottom far corner   */
505 #define LTN     2  /* left top near corner     */
506 #define LTF     3  /* left top far corner      */
507 #define RBN     4  /* right bottom near corner */
508 #define RBF     5  /* right bottom far corner  */
509 #define RTN     6  /* right top near corner    */
510 #define RTF     7  /* right top far corner     */
511
512 /* the LBN corner of cube (i, j, k), corresponds with location
513  * (i-0.5)*size, (j-0.5)*size, (k-0.5)*size) */
514
515 #define HASHBIT     (5)
516 #define HASHSIZE    (size_t)(1<<(3*HASHBIT))   /*! < hash table size (32768) */
517
518 #define HASH(i,j,k) ((((( (i) & 31)<<5) | ( (j) & 31))<<5 ) | ( (k) & 31) )
519
520 #define MB_BIT(i, bit) (((i)>>(bit))&1)
521 #define FLIP(i,bit) ((i)^1<<(bit)) /* flip the given bit of i */
522
523
524 /* **************** POLYGONIZATION ************************ */
525
526 void calc_mballco(MetaElem *ml, float *vec)
527 {
528         if(ml->mat) {
529                 mul_m4_v3((float ( * )[4])ml->mat, vec);
530         }
531 }
532
533 float densfunc(MetaElem *ball, float x, float y, float z)
534 {
535         float dist2 = 0.0, dx, dy, dz;
536         float vec[3];
537
538         vec[0]= x;
539         vec[1]= y;
540         vec[2]= z;
541         mul_m4_v3((float ( * )[4])ball->imat, vec);
542         dx= vec[0];
543         dy= vec[1];
544         dz= vec[2];
545         
546         if(ball->type==MB_BALL) {
547         }
548         else if(ball->type==MB_TUBEX) {
549                 if( dx > ball->len) dx-= ball->len;
550                 else if(dx< -ball->len) dx+= ball->len;
551                 else dx= 0.0;
552         }
553         else if(ball->type==MB_TUBEY) {
554                 if( dy > ball->len) dy-= ball->len;
555                 else if(dy< -ball->len) dy+= ball->len;
556                 else dy= 0.0;
557         }
558         else if(ball->type==MB_TUBEZ) {
559                 if( dz > ball->len) dz-= ball->len;
560                 else if(dz< -ball->len) dz+= ball->len;
561                 else dz= 0.0;
562         }
563         else if(ball->type==MB_TUBE) {
564                 if( dx > ball->expx) dx-= ball->expx;
565                 else if(dx< -ball->expx) dx+= ball->expx;
566                 else dx= 0.0;
567         }
568         else if(ball->type==MB_PLANE) {
569                 if( dx > ball->expx) dx-= ball->expx;
570                 else if(dx< -ball->expx) dx+= ball->expx;
571                 else dx= 0.0;
572                 if( dy > ball->expy) dy-= ball->expy;
573                 else if(dy< -ball->expy) dy+= ball->expy;
574                 else dy= 0.0;
575         }
576         else if(ball->type==MB_ELIPSOID) {
577                 dx *= 1/ball->expx;
578                 dy *= 1/ball->expy;
579                 dz *= 1/ball->expz;
580         }
581         else if(ball->type==MB_CUBE) {
582                 if( dx > ball->expx) dx-= ball->expx;
583                 else if(dx< -ball->expx) dx+= ball->expx;
584                 else dx= 0.0;
585                 if( dy > ball->expy) dy-= ball->expy;
586                 else if(dy< -ball->expy) dy+= ball->expy;
587                 else dy= 0.0;
588                 if( dz > ball->expz) dz-= ball->expz;
589                 else if(dz< -ball->expz) dz+= ball->expz;
590                 else dz= 0.0;
591         }
592
593         dist2= (dx*dx + dy*dy + dz*dz);
594
595         if(ball->flag & MB_NEGATIVE) {
596                 dist2= 1.0f-(dist2/ball->rad2);
597                 if(dist2 < 0.0f) return 0.5f;
598
599                 return 0.5f-ball->s*dist2*dist2*dist2;
600         }
601         else {
602                 dist2= 1.0f-(dist2/ball->rad2);
603                 if(dist2 < 0.0f) return -0.5f;
604
605                 return ball->s*dist2*dist2*dist2 -0.5f;
606         }
607 }
608
609 octal_node* find_metaball_octal_node(octal_node *node, float x, float y, float z, short depth)
610 {
611         if(!depth) return node;
612         
613         if(z < node->z){
614                 if(y < node->y){
615                         if(x < node->x){
616                                 if(node->nodes[0])
617                                         return find_metaball_octal_node(node->nodes[0],x,y,z,depth--);
618                                 else
619                                         return node;
620                         }
621                         else{
622                                 if(node->nodes[1])
623                                         return find_metaball_octal_node(node->nodes[1],x,y,z,depth--);
624                                 else
625                                         return node;
626                         }
627                 }
628                 else{
629                         if(x < node->x){
630                                 if(node->nodes[3])
631                                         return find_metaball_octal_node(node->nodes[3],x,y,z,depth--);
632                                 else
633                                         return node;
634                         }
635                         else{
636                                 if(node->nodes[2])
637                                         return find_metaball_octal_node(node->nodes[2],x,y,z,depth--);
638                                 else
639                                         return node;
640                         }               
641                 }
642         }
643         else{
644                 if(y < node->y){
645                         if(x < node->x){
646                                 if(node->nodes[4])
647                                         return find_metaball_octal_node(node->nodes[4],x,y,z,depth--);
648                                 else
649                                         return node;
650                         }
651                         else{
652                                 if(node->nodes[5])
653                                         return find_metaball_octal_node(node->nodes[5],x,y,z,depth--);
654                                 else
655                                         return node;
656                         }
657                 }
658                 else{
659                         if(x < node->x){
660                                 if(node->nodes[7])
661                                         return find_metaball_octal_node(node->nodes[7],x,y,z,depth--);
662                                 else
663                                         return node;
664                         }
665                         else{
666                                 if(node->nodes[6])
667                                         return find_metaball_octal_node(node->nodes[6],x,y,z,depth--);
668                                 else
669                                         return node;
670                         }               
671                 }
672         }
673         
674         return node;
675 }
676
677 float metaball(float x, float y, float z)
678 /*  float x, y, z; */
679 {
680         struct octal_node *node;
681         struct ml_pointer *ml_p;
682         float dens=0;
683         int a;
684         
685         if(totelem > 1){
686                 node= find_metaball_octal_node(metaball_tree->first, x, y, z, metaball_tree->depth);
687                 if(node){
688                         ml_p= node->elems.first;
689
690                         while(ml_p){
691                                 dens+=densfunc(ml_p->ml, x, y, z);
692                                 ml_p= ml_p->next;
693                         }
694
695                         dens+= -0.5f*(metaball_tree->pos - node->pos);
696                         dens+= 0.5f*(metaball_tree->neg - node->neg);
697                 }
698                 else{
699                         for(a=0; a<totelem; a++) {
700                                 dens+= densfunc( mainb[a], x, y, z);
701                         }
702                 }
703         }
704         else{
705                 dens+= densfunc( mainb[0], x, y, z);
706         }
707
708         return thresh - dens;
709 }
710
711 /* ******************************************** */
712
713 static int *indices=NULL;
714 static int totindex, curindex;
715
716
717 void accum_mballfaces(int i1, int i2, int i3, int i4)
718 {
719         int *newi, *cur;
720         /* static int i=0; I would like to delete altogether, but I don't dare to, yet */
721
722         if(totindex==curindex) {
723                 totindex+= 256;
724                 newi= MEM_mallocN(4*sizeof(int)*totindex, "vertindex");
725                 
726                 if(indices) {
727                         memcpy(newi, indices, 4*sizeof(int)*(totindex-256));
728                         MEM_freeN(indices);
729                 }
730                 indices= newi;
731         }
732         
733         cur= indices+4*curindex;
734
735         /* displists now support array drawing, we treat tri's as fake quad */
736         
737         cur[0]= i1;
738         cur[1]= i2;
739         cur[2]= i3;
740         if(i4==0)
741                 cur[3]= i3;
742         else 
743                 cur[3]= i4;
744         
745         curindex++;
746
747 }
748
749 /* ******************* MEMORY MANAGEMENT *********************** */
750 void *new_pgn_element(int size)
751 {
752         /* during polygonize 1000s of elements are allocated
753          * and never freed in between. Freeing only done at the end.
754          */
755         int blocksize= 16384;
756         static int offs= 0;             /* the current free address */
757         static struct pgn_elements *cur= NULL;
758         static ListBase lb= {NULL, NULL};
759         void *adr;
760         
761         if(size>10000 || size==0) {
762                 printf("incorrect use of new_pgn_element\n");
763         }
764         else if(size== -1) {
765                 cur= lb.first;
766                 while(cur) {
767                         MEM_freeN(cur->data);
768                         cur= cur->next;
769                 }
770                 BLI_freelistN(&lb);
771                 
772                 return NULL;    
773         }
774         
775         size= 4*( (size+3)/4 );
776         
777         if(cur) {
778                 if(size+offs < blocksize) {
779                         adr= (void *) (cur->data+offs);
780                          offs+= size;
781                         return adr;
782                 }
783         }
784         
785         cur= MEM_callocN( sizeof(struct pgn_elements), "newpgn");
786         cur->data= MEM_callocN(blocksize, "newpgn");
787         BLI_addtail(&lb, cur);
788         
789         offs= size;
790         return cur->data;
791 }
792
793 void freepolygonize(PROCESS *p)
794 {
795         MEM_freeN(p->corners);
796         MEM_freeN(p->edges);
797         MEM_freeN(p->centers);
798
799         new_pgn_element(-1);
800         
801         if(p->vertices.ptr) MEM_freeN(p->vertices.ptr);
802 }
803
804 /**** Cubical Polygonization (optional) ****/
805
806 #define LB      0  /* left bottom edge  */
807 #define LT      1  /* left top edge     */
808 #define LN      2  /* left near edge    */
809 #define LF      3  /* left far edge     */
810 #define RB      4  /* right bottom edge */
811 #define RT      5  /* right top edge    */
812 #define RN      6  /* right near edge   */
813 #define RF      7  /* right far edge    */
814 #define BN      8  /* bottom near edge  */
815 #define BF      9  /* bottom far edge   */
816 #define TN      10 /* top near edge     */
817 #define TF      11 /* top far edge      */
818
819 static INTLISTS *cubetable[256];
820
821 /* edge: LB, LT, LN, LF, RB, RT, RN, RF, BN, BF, TN, TF */
822 static int corner1[12]     = {
823         LBN,LTN,LBN,LBF,RBN,RTN,RBN,RBF,LBN,LBF,LTN,LTF};
824 static int corner2[12]     = {
825         LBF,LTF,LTN,LTF,RBF,RTF,RTN,RTF,RBN,RBF,RTN,RTF};
826 static int leftface[12]    = {
827         B,  L,  L,  F,  R,  T,  N,  R,  N,  B,  T,  F};
828 /* face on left when going corner1 to corner2 */
829 static int rightface[12]   = {
830         L,  T,  N,  L,  B,  R,  R,  F,  B,  F,  N,  T};
831 /* face on right when going corner1 to corner2 */
832
833
834 /* docube: triangulate the cube directly, without decomposition */
835
836 void docube(CUBE *cube, PROCESS *p, MetaBall *mb)
837 {
838         INTLISTS *polys;
839         CORNER *c1, *c2;
840         int i, index = 0, count, indexar[8];
841         
842         for (i = 0; i < 8; i++) if (cube->corners[i]->value > 0.0f) index += (1<<i);
843         
844         for (polys = cubetable[index]; polys; polys = polys->next) {
845                 INTLIST *edges;
846                 
847                 count = 0;
848                 
849                 for (edges = polys->list; edges; edges = edges->next) {
850                         c1 = cube->corners[corner1[edges->i]];
851                         c2 = cube->corners[corner2[edges->i]];
852                         
853                         indexar[count] = vertid(c1, c2, p, mb);
854                         count++;
855                 }
856                 if(count>2) {
857                         switch(count) {
858                         case 3:
859                                 accum_mballfaces(indexar[2], indexar[1], indexar[0], 0);
860                                 break;
861                         case 4:
862                                 if(indexar[0]==0) accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
863                                 else accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
864                                 break;
865                         case 5:
866                                 if(indexar[0]==0) accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
867                                 else accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
868
869                                 accum_mballfaces(indexar[4], indexar[3], indexar[0], 0);
870                                 break;
871                         case 6:
872                                 if(indexar[0]==0) {
873                                         accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
874                                         accum_mballfaces(indexar[0], indexar[5], indexar[4], indexar[3]);
875                                 }
876                                 else {
877                                         accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
878                                         accum_mballfaces(indexar[5], indexar[4], indexar[3], indexar[0]);
879                                 }
880                                 break;
881                         case 7:
882                                 if(indexar[0]==0) {
883                                         accum_mballfaces(indexar[0], indexar[3], indexar[2], indexar[1]);
884                                         accum_mballfaces(indexar[0], indexar[5], indexar[4], indexar[3]);
885                                 }
886                                 else {
887                                         accum_mballfaces(indexar[3], indexar[2], indexar[1], indexar[0]);
888                                         accum_mballfaces(indexar[5], indexar[4], indexar[3], indexar[0]);
889                                 }
890                                 
891                                 accum_mballfaces(indexar[6], indexar[5], indexar[0], 0);
892                                 
893                                 break;
894                         }
895                 }
896         }
897 }
898
899
900 /* testface: given cube at lattice (i, j, k), and four corners of face,
901  * if surface crosses face, compute other four corners of adjacent cube
902  * and add new cube to cube stack */
903
904 void testface(int i, int j, int k, CUBE* old, int bit, int c1, int c2, int c3, int c4, PROCESS *p)
905 {
906         CUBE newc;
907         CUBES *oldcubes = p->cubes;
908         CORNER *corn1, *corn2, *corn3, *corn4;
909         int n, pos;
910
911         corn1= old->corners[c1];
912         corn2= old->corners[c2];
913         corn3= old->corners[c3];
914         corn4= old->corners[c4];
915         
916         pos = corn1->value > 0.0f ? 1 : 0;
917
918         /* test if no surface crossing */
919         if( (corn2->value > 0) == pos && (corn3->value > 0) == pos && (corn4->value > 0) == pos) return;
920         /* test if cube out of bounds */
921         /*if ( abs(i) > p->bounds || abs(j) > p->bounds || abs(k) > p->bounds) return;*/
922         /* test if already visited (always as last) */
923         if (setcenter(p->centers, i, j, k)) return;
924
925
926         /* create new cube and add cube to top of stack: */
927         p->cubes = (CUBES *) new_pgn_element(sizeof(CUBES));
928         p->cubes->next = oldcubes;
929         
930         newc.i = i;
931         newc.j = j;
932         newc.k = k;
933         for (n = 0; n < 8; n++) newc.corners[n] = NULL;
934         
935         newc.corners[FLIP(c1, bit)] = corn1;
936         newc.corners[FLIP(c2, bit)] = corn2;
937         newc.corners[FLIP(c3, bit)] = corn3;
938         newc.corners[FLIP(c4, bit)] = corn4;
939
940         if(newc.corners[0]==NULL) newc.corners[0] = setcorner(p, i, j, k);
941         if(newc.corners[1]==NULL) newc.corners[1] = setcorner(p, i, j, k+1);
942         if(newc.corners[2]==NULL) newc.corners[2] = setcorner(p, i, j+1, k);
943         if(newc.corners[3]==NULL) newc.corners[3] = setcorner(p, i, j+1, k+1);
944         if(newc.corners[4]==NULL) newc.corners[4] = setcorner(p, i+1, j, k);
945         if(newc.corners[5]==NULL) newc.corners[5] = setcorner(p, i+1, j, k+1);
946         if(newc.corners[6]==NULL) newc.corners[6] = setcorner(p, i+1, j+1, k);
947         if(newc.corners[7]==NULL) newc.corners[7] = setcorner(p, i+1, j+1, k+1);
948
949         p->cubes->cube= newc;   
950 }
951
952 /* setcorner: return corner with the given lattice location
953    set (and cache) its function value */
954
955 CORNER *setcorner (PROCESS* p, int i, int j, int k)
956 {
957         /* for speed, do corner value caching here */
958         CORNER *c;
959         int index;
960
961         /* does corner exist? */
962         index = HASH(i, j, k);
963         c = p->corners[index];
964         
965         for (; c != NULL; c = c->next) {
966                 if (c->i == i && c->j == j && c->k == k) {
967                         return c;
968                 }
969         }
970
971         c = (CORNER *) new_pgn_element(sizeof(CORNER));
972
973         c->i = i; 
974         c->x = ((float)i-0.5f)*p->size;
975         c->j = j; 
976         c->y = ((float)j-0.5f)*p->size;
977         c->k = k; 
978         c->z = ((float)k-0.5f)*p->size;
979         c->value = p->function(c->x, c->y, c->z);
980         
981         c->next = p->corners[index];
982         p->corners[index] = c;
983         
984         return c;
985 }
986
987
988 /* nextcwedge: return next clockwise edge from given edge around given face */
989
990 int nextcwedge (int edge, int face)
991 {
992         switch (edge) {
993         case LB: 
994                 return (face == L)? LF : BN;
995         case LT: 
996                 return (face == L)? LN : TF;
997         case LN: 
998                 return (face == L)? LB : TN;
999         case LF: 
1000                 return (face == L)? LT : BF;
1001         case RB: 
1002                 return (face == R)? RN : BF;
1003         case RT: 
1004                 return (face == R)? RF : TN;
1005         case RN: 
1006                 return (face == R)? RT : BN;
1007         case RF: 
1008                 return (face == R)? RB : TF;
1009         case BN: 
1010                 return (face == B)? RB : LN;
1011         case BF: 
1012                 return (face == B)? LB : RF;
1013         case TN: 
1014                 return (face == T)? LT : RN;
1015         case TF: 
1016                 return (face == T)? RT : LF;
1017         }
1018         return 0;
1019 }
1020
1021
1022 /* otherface: return face adjoining edge that is not the given face */
1023
1024 int otherface (int edge, int face)
1025 {
1026         int other = leftface[edge];
1027         return face == other? rightface[edge] : other;
1028 }
1029
1030
1031 /* makecubetable: create the 256 entry table for cubical polygonization */
1032
1033 void makecubetable (void)
1034 {
1035         static int isdone= 0;
1036         int i, e, c, done[12], pos[8];
1037
1038         if(isdone) return;
1039         isdone= 1;
1040
1041         for (i = 0; i < 256; i++) {
1042                 for (e = 0; e < 12; e++) done[e] = 0;
1043                 for (c = 0; c < 8; c++) pos[c] = MB_BIT(i, c);
1044                 for (e = 0; e < 12; e++)
1045                         if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) {
1046                                 INTLIST *ints = NULL;
1047                                 INTLISTS *lists = (INTLISTS *) MEM_callocN(sizeof(INTLISTS), "mball_intlist");
1048                                 int start = e, edge = e;
1049                                 
1050                                 /* get face that is to right of edge from pos to neg corner: */
1051                                 int face = pos[corner1[e]]? rightface[e] : leftface[e];
1052                                 
1053                                 while (1) {
1054                                         edge = nextcwedge(edge, face);
1055                                         done[edge] = 1;
1056                                         if (pos[corner1[edge]] != pos[corner2[edge]]) {
1057                                                 INTLIST *tmp = ints;
1058                                                 
1059                                                 ints = (INTLIST *) MEM_callocN(sizeof(INTLIST), "mball_intlist");
1060                                                 ints->i = edge;
1061                                                 ints->next = tmp; /* add edge to head of list */
1062                                                 
1063                                                 if (edge == start) break;
1064                                                 face = otherface(edge, face);
1065                                         }
1066                                 }
1067                                 lists->list = ints; /* add ints to head of table entry */
1068                                 lists->next = cubetable[i];
1069                                 cubetable[i] = lists;
1070                         }
1071         }
1072 }
1073
1074 void BKE_freecubetable(void)
1075 {
1076         int i;
1077         INTLISTS *lists, *nlists;
1078         INTLIST *ints, *nints;
1079
1080         for (i = 0; i < 256; i++) {
1081                 lists= cubetable[i];
1082                 while(lists) {
1083                         nlists= lists->next;
1084                         
1085                         ints= lists->list;
1086                         while(ints) {
1087                                 nints= ints->next;
1088                                 MEM_freeN(ints);
1089                                 ints= nints;
1090                         }
1091                         
1092                         MEM_freeN(lists);
1093                         lists= nlists;
1094                 }
1095                 cubetable[i]= NULL;
1096         }
1097 }
1098
1099 /**** Storage ****/
1100
1101 /* setcenter: set (i,j,k) entry of table[]
1102  * return 1 if already set; otherwise, set and return 0 */
1103
1104 int setcenter(CENTERLIST *table[], int i, int j, int k)
1105 {
1106         int index;
1107         CENTERLIST *newc, *l, *q;
1108
1109         index= HASH(i, j, k);
1110         q= table[index];
1111
1112         for (l = q; l != NULL; l = l->next) {
1113                 if (l->i == i && l->j == j && l->k == k) return 1;
1114         }
1115         
1116         newc = (CENTERLIST *) new_pgn_element(sizeof(CENTERLIST));
1117         newc->i = i; 
1118         newc->j = j; 
1119         newc->k = k; 
1120         newc->next = q;
1121         table[index] = newc;
1122         
1123         return 0;
1124 }
1125
1126
1127 /* setedge: set vertex id for edge */
1128
1129 void setedge (EDGELIST *table[],
1130                           int i1, int j1,
1131                           int k1, int i2,
1132                           int j2, int k2,
1133                           int vid)
1134 {
1135         unsigned int index;
1136         EDGELIST *newe;
1137         
1138         if (i1>i2 || (i1==i2 && (j1>j2 || (j1==j2 && k1>k2)))) {
1139                 int t=i1; 
1140                 i1=i2; 
1141                 i2=t; 
1142                 t=j1; 
1143                 j1=j2; 
1144                 j2=t; 
1145                 t=k1; 
1146                 k1=k2; 
1147                 k2=t;
1148         }
1149         index = HASH(i1, j1, k1) + HASH(i2, j2, k2);
1150         newe = (EDGELIST *) new_pgn_element(sizeof(EDGELIST));
1151         newe->i1 = i1; 
1152         newe->j1 = j1; 
1153         newe->k1 = k1;
1154         newe->i2 = i2; 
1155         newe->j2 = j2; 
1156         newe->k2 = k2;
1157         newe->vid = vid;
1158         newe->next = table[index];
1159         table[index] = newe;
1160 }
1161
1162
1163 /* getedge: return vertex id for edge; return -1 if not set */
1164
1165 int getedge (EDGELIST *table[],
1166                          int i1, int j1, int k1,
1167                          int i2, int j2, int k2)
1168 {
1169         EDGELIST *q;
1170         
1171         if (i1>i2 || (i1==i2 && (j1>j2 || (j1==j2 && k1>k2)))) {
1172                 int t=i1; 
1173                 i1=i2; 
1174                 i2=t; 
1175                 t=j1; 
1176                 j1=j2; 
1177                 j2=t; 
1178                 t=k1; 
1179                 k1=k2; 
1180                 k2=t;
1181         }
1182         q = table[HASH(i1, j1, k1)+HASH(i2, j2, k2)];
1183         for (; q != NULL; q = q->next)
1184                 if (q->i1 == i1 && q->j1 == j1 && q->k1 == k1 &&
1185                         q->i2 == i2 && q->j2 == j2 && q->k2 == k2)
1186                         return q->vid;
1187         return -1;
1188 }
1189
1190
1191 /**** Vertices ****/
1192
1193 #undef R
1194
1195
1196
1197 /* vertid: return index for vertex on edge:
1198  * c1->value and c2->value are presumed of different sign
1199  * return saved index if any; else compute vertex and save */
1200
1201 /* addtovertices: add v to sequence of vertices */
1202
1203 void addtovertices (VERTICES *vertices, VERTEX v)
1204 {
1205         if (vertices->count == vertices->max) {
1206                 int i;
1207                 VERTEX *newv;
1208                 vertices->max = vertices->count == 0 ? 10 : 2*vertices->count;
1209                 newv = (VERTEX *) MEM_callocN(vertices->max * sizeof(VERTEX), "addtovertices");
1210                 
1211                 for (i = 0; i < vertices->count; i++) newv[i] = vertices->ptr[i];
1212                 
1213                 if (vertices->ptr != NULL) MEM_freeN(vertices->ptr);
1214                 vertices->ptr = newv;
1215         }
1216         vertices->ptr[vertices->count++] = v;
1217 }
1218
1219 /* vnormal: compute unit length surface normal at point */
1220
1221 void vnormal (MB_POINT *point, PROCESS *p, MB_POINT *v)
1222 {
1223         float delta= 0.2f*p->delta;
1224         float f = p->function(point->x, point->y, point->z);
1225
1226         v->x = p->function(point->x+delta, point->y, point->z)-f;
1227         v->y = p->function(point->x, point->y+delta, point->z)-f;
1228         v->z = p->function(point->x, point->y, point->z+delta)-f;
1229         f = sqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
1230
1231         if (f != 0.0f) {
1232                 v->x /= f; 
1233                 v->y /= f; 
1234                 v->z /= f;
1235         }
1236         
1237         if(FALSE) {
1238                 MB_POINT temp;
1239                 
1240                 delta *= 2.0f;
1241                 
1242                 f = p->function(point->x, point->y, point->z);
1243         
1244                 temp.x = p->function(point->x+delta, point->y, point->z)-f;
1245                 temp.y = p->function(point->x, point->y+delta, point->z)-f;
1246                 temp.z = p->function(point->x, point->y, point->z+delta)-f;
1247                 f = sqrtf(temp.x*temp.x + temp.y*temp.y + temp.z*temp.z);
1248         
1249                 if (f != 0.0f) {
1250                         temp.x /= f; 
1251                         temp.y /= f; 
1252                         temp.z /= f;
1253                         
1254                         v->x+= temp.x;
1255                         v->y+= temp.y;
1256                         v->z+= temp.z;
1257                         
1258                         f = sqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
1259                 
1260                         if (f != 0.0f) {
1261                                 v->x /= f; 
1262                                 v->y /= f; 
1263                                 v->z /= f;
1264                         }
1265                 }
1266         }
1267         
1268 }
1269
1270
1271 int vertid (CORNER *c1, CORNER *c2, PROCESS *p, MetaBall *mb)
1272 {
1273         VERTEX v;
1274         MB_POINT a, b;
1275         int vid = getedge(p->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k);
1276
1277         if (vid != -1) return vid;                           /* previously computed */
1278         a.x = c1->x; 
1279         a.y = c1->y; 
1280         a.z = c1->z;
1281         b.x = c2->x; 
1282         b.y = c2->y; 
1283         b.z = c2->z;
1284
1285         converge(&a, &b, c1->value, c2->value, p->function, &v.position, mb, 1); /* position */
1286         vnormal(&v.position, p, &v.normal);
1287
1288         addtovertices(&p->vertices, v);                    /* save vertex */
1289         vid = p->vertices.count-1;
1290         setedge(p->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k, vid);
1291         
1292         return vid;
1293 }
1294
1295
1296
1297
1298 /* converge: from two points of differing sign, converge to zero crossing */
1299 /* watch it: p1 and p2 are used to calculate */
1300 void converge (MB_POINT *p1, MB_POINT *p2, float v1, float v2,
1301                            float (*function)(float, float, float), MB_POINT *p, MetaBall *mb, int f)
1302 {
1303         int i = 0;
1304         MB_POINT pos, neg;
1305         float positive = 0.0f, negative = 0.0f;
1306         float dx = 0.0f ,dy = 0.0f ,dz = 0.0f;
1307         
1308         if (v1 < 0) {
1309                 pos= *p2;
1310                 neg= *p1;
1311                 positive = v2;
1312                 negative = v1;
1313         }
1314         else {
1315                 pos= *p1;
1316                 neg= *p2;
1317                 positive = v1;
1318                 negative = v2;
1319         }
1320
1321         dx = pos.x - neg.x;
1322         dy = pos.y - neg.y;
1323         dz = pos.z - neg.z;
1324
1325 /* Approximation by linear interpolation is faster then binary subdivision,
1326  * but it results sometimes (mb->thresh < 0.2) into the strange results */
1327         if((mb->thresh > 0.2f) && (f==1)){
1328         if((dy == 0.0f) && (dz == 0.0f)){
1329                 p->x = neg.x - negative*dx/(positive-negative);
1330                 p->y = neg.y;
1331                 p->z = neg.z;
1332                 return;
1333         }
1334           if((dx == 0.0f) && (dz == 0.0f)){
1335                 p->x = neg.x;
1336                 p->y = neg.y - negative*dy/(positive-negative);
1337                 p->z = neg.z;
1338                 return;
1339         }
1340         if((dx == 0.0f) && (dy == 0.0f)){
1341                 p->x = neg.x;
1342                 p->y = neg.y;
1343                 p->z = neg.z - negative*dz/(positive-negative);
1344                 return;
1345         }
1346         }
1347
1348         if((dy == 0.0f) && (dz == 0.0f)){
1349                 p->y = neg.y;
1350                 p->z = neg.z;
1351                 while (1) {
1352                         if (i++ == RES) return;
1353                         p->x = 0.5f*(pos.x + neg.x);
1354                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.x = p->x; else neg.x = p->x;
1355                 }
1356         }
1357
1358         if((dx == 0.0f) && (dz == 0.0f)){
1359                 p->x = neg.x;
1360                 p->z = neg.z;
1361                 while (1) {
1362                         if (i++ == RES) return;
1363                         p->y = 0.5f*(pos.y + neg.y);
1364                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.y = p->y; else neg.y = p->y;
1365                 }
1366           }
1367    
1368         if((dx == 0.0f) && (dy == 0.0f)){
1369                 p->x = neg.x;
1370                 p->y = neg.y;
1371                 while (1) {
1372                         if (i++ == RES) return;
1373                         p->z = 0.5f*(pos.z + neg.z);
1374                         if ((function(p->x,p->y,p->z)) > 0.0f)  pos.z = p->z; else neg.z = p->z;
1375                 }
1376         }
1377
1378         /* This is necessary to find start point */
1379         while (1) {
1380                 p->x = 0.5f*(pos.x + neg.x);
1381                 p->y = 0.5f*(pos.y + neg.y);
1382                 p->z = 0.5f*(pos.z + neg.z);
1383
1384                 if (i++ == RES) return;
1385    
1386                 if ((function(p->x, p->y, p->z)) > 0.0f){
1387                         pos.x = p->x;
1388                         pos.y = p->y;
1389                         pos.z = p->z;
1390                 }
1391                 else{
1392                         neg.x = p->x;
1393                         neg.y = p->y;
1394                         neg.z = p->z;
1395                 }
1396         }
1397 }
1398
1399 /* ************************************** */
1400 void add_cube(PROCESS *mbproc, int i, int j, int k, int count)
1401 {
1402         CUBES *ncube;
1403         int n;
1404         int a, b, c;
1405
1406         /* hmmm, not only one, but eight cube will be added on the stack 
1407          * ... */
1408         for(a=i-1; a<i+count; a++)
1409                 for(b=j-1; b<j+count; b++)
1410                         for(c=k-1; c<k+count; c++) {
1411                                 /* test if cube has been found before */
1412                                 if( setcenter(mbproc->centers, a, b, c)==0 ) {
1413                                         /* push cube on stack: */
1414                                         ncube= (CUBES *) new_pgn_element(sizeof(CUBES));
1415                                         ncube->next= mbproc->cubes;
1416                                         mbproc->cubes= ncube;
1417
1418                                         ncube->cube.i= a;
1419                                         ncube->cube.j= b;
1420                                         ncube->cube.k= c;
1421
1422                                         /* set corners of initial cube: */
1423                                         for (n = 0; n < 8; n++)
1424                                         ncube->cube.corners[n] = setcorner(mbproc, a+MB_BIT(n,2), b+MB_BIT(n,1), c+MB_BIT(n,0));
1425                                 }
1426                         }
1427 }
1428
1429
1430 void find_first_points(PROCESS *mbproc, MetaBall *mb, int a)
1431 {
1432         MB_POINT IN, in, OUT, out; /*point;*/
1433         MetaElem *ml;
1434         int i, j, k, c_i, c_j, c_k;
1435         int index[3]={1,0,-1};
1436         float f =0.0f;
1437         float in_v /*, out_v*/;
1438         MB_POINT workp;
1439         float tmp_v, workp_v, max_len, len, dx, dy, dz, nx, ny, nz, MAXN;
1440
1441         ml = mainb[a];
1442
1443         f = 1-(mb->thresh/ml->s);
1444
1445         /* Skip, when Stiffness of MetaElement is too small ... MetaElement can't be
1446          * visible alone ... but still can influence others MetaElements :-) */
1447         if(f > 0.0f) {
1448                 OUT.x = IN.x = in.x= 0.0;
1449                 OUT.y = IN.y = in.y= 0.0;
1450                 OUT.z = IN.z = in.z= 0.0;
1451
1452                 calc_mballco(ml, (float *)&in);
1453                 in_v = mbproc->function(in.x, in.y, in.z);
1454
1455                 for(i=0;i<3;i++){
1456                         switch (ml->type) {
1457                                 case MB_BALL:
1458                                         OUT.x = out.x= IN.x + index[i]*ml->rad;
1459                                         break;
1460                                 case MB_TUBE:
1461                                 case MB_PLANE:
1462                                 case MB_ELIPSOID:
1463                                 case MB_CUBE:
1464                                         OUT.x = out.x= IN.x + index[i]*(ml->expx + ml->rad);
1465                                         break;
1466                         }
1467
1468                         for(j=0;j<3;j++) {
1469                                 switch (ml->type) {
1470                                         case MB_BALL:
1471                                                 OUT.y = out.y= IN.y + index[j]*ml->rad;
1472                                                 break;
1473                                         case MB_TUBE:
1474                                         case MB_PLANE:
1475                                         case MB_ELIPSOID:
1476                                         case MB_CUBE:
1477                                                 OUT.y = out.y= IN.y + index[j]*(ml->expy + ml->rad);
1478                                                 break;
1479                                 }
1480                         
1481                                 for(k=0;k<3;k++) {
1482                                         out.x = OUT.x;
1483                                         out.y = OUT.y;
1484                                         switch (ml->type) {
1485                                                 case MB_BALL:
1486                                                 case MB_TUBE:
1487                                                 case MB_PLANE:
1488                                                         out.z= IN.z + index[k]*ml->rad;
1489                                                         break;
1490                                                 case MB_ELIPSOID:
1491                                                 case MB_CUBE:
1492                                                         out.z= IN.z + index[k]*(ml->expz + ml->rad);
1493                                                         break;
1494                                         }
1495
1496                                         calc_mballco(ml, (float *)&out);
1497
1498                                         /*out_v = mbproc->function(out.x, out.y, out.z);*/ /*UNUSED*/
1499
1500                                         /* find "first points" on Implicit Surface of MetaElemnt ml */
1501                                         workp.x = in.x;
1502                                         workp.y = in.y;
1503                                         workp.z = in.z;
1504                                         workp_v = in_v;
1505                                         max_len = sqrtf((out.x-in.x)*(out.x-in.x) + (out.y-in.y)*(out.y-in.y) + (out.z-in.z)*(out.z-in.z));
1506
1507                                         nx = abs((out.x - in.x)/mbproc->size);
1508                                         ny = abs((out.y - in.y)/mbproc->size);
1509                                         nz = abs((out.z - in.z)/mbproc->size);
1510                                         
1511                                         MAXN = MAX3(nx,ny,nz);
1512                                         if(MAXN!=0.0f) {
1513                                                 dx = (out.x - in.x)/MAXN;
1514                                                 dy = (out.y - in.y)/MAXN;
1515                                                 dz = (out.z - in.z)/MAXN;
1516
1517                                                 len = 0.0;
1518                                                 while(len<=max_len) {
1519                                                         workp.x += dx;
1520                                                         workp.y += dy;
1521                                                         workp.z += dz;
1522                                                         /* compute value of implicite function */
1523                                                         tmp_v = mbproc->function(workp.x, workp.y, workp.z);
1524                                                         /* add cube to the stack, when value of implicite function crosses zero value */
1525                                                         if((tmp_v<0.0f && workp_v>=0.0f)||(tmp_v>0.0f && workp_v<=0.0f)) {
1526
1527                                                                 /* indexes of CUBE, which includes "first point" */
1528                                                                 c_i= (int)floor(workp.x/mbproc->size);
1529                                                                 c_j= (int)floor(workp.y/mbproc->size);
1530                                                                 c_k= (int)floor(workp.z/mbproc->size);
1531                                                                 
1532                                                                 /* add CUBE (with indexes c_i, c_j, c_k) to the stack,
1533                                                                  * this cube includes found point of Implicit Surface */
1534                                                                 if (ml->flag & MB_NEGATIVE)
1535                                                                         add_cube(mbproc, c_i, c_j, c_k, 2);
1536                                                                 else
1537                                                                         add_cube(mbproc, c_i, c_j, c_k, 1);
1538                                                         }
1539                                                         len = sqrtf((workp.x-in.x)*(workp.x-in.x) + (workp.y-in.y)*(workp.y-in.y) + (workp.z-in.z)*(workp.z-in.z));
1540                                                         workp_v = tmp_v;
1541
1542                                                 }
1543                                         }
1544                                 }
1545                         }
1546                 }
1547         }
1548 }
1549
1550 void polygonize(PROCESS *mbproc, MetaBall *mb)
1551 {
1552         CUBE c;
1553         int a;
1554
1555         mbproc->vertices.count = mbproc->vertices.max = 0;
1556         mbproc->vertices.ptr = NULL;
1557
1558         /* allocate hash tables and build cube polygon table: */
1559         mbproc->centers = MEM_callocN(HASHSIZE * sizeof(CENTERLIST *), "mbproc->centers");
1560         mbproc->corners = MEM_callocN(HASHSIZE * sizeof(CORNER *), "mbproc->corners");
1561         mbproc->edges = MEM_callocN(2*HASHSIZE * sizeof(EDGELIST *), "mbproc->edges");
1562         makecubetable();
1563
1564         for(a=0; a<totelem; a++) {
1565
1566                 /* try to find 8 points on the surface for each MetaElem */
1567                 find_first_points(mbproc, mb, a);       
1568         }
1569
1570         /* polygonize all MetaElems of current MetaBall */
1571         while (mbproc->cubes != NULL) { /* process active cubes till none left */
1572                 c = mbproc->cubes->cube;
1573
1574                 /* polygonize the cube directly: */
1575                 docube(&c, mbproc, mb);
1576                 
1577                 /* pop current cube from stack */
1578                 mbproc->cubes = mbproc->cubes->next;
1579                 
1580                 /* test six face directions, maybe add to stack: */
1581                 testface(c.i-1, c.j, c.k, &c, 2, LBN, LBF, LTN, LTF, mbproc);
1582                 testface(c.i+1, c.j, c.k, &c, 2, RBN, RBF, RTN, RTF, mbproc);
1583                 testface(c.i, c.j-1, c.k, &c, 1, LBN, LBF, RBN, RBF, mbproc);
1584                 testface(c.i, c.j+1, c.k, &c, 1, LTN, LTF, RTN, RTF, mbproc);
1585                 testface(c.i, c.j, c.k-1, &c, 0, LBN, LTN, RBN, RTN, mbproc);
1586                 testface(c.i, c.j, c.k+1, &c, 0, LBF, LTF, RBF, RTF, mbproc);
1587         }
1588 }
1589
1590 float init_meta(Scene *scene, Object *ob)       /* return totsize */
1591 {
1592         Scene *sce_iter= scene;
1593         Base *base;
1594         Object *bob;
1595         MetaBall *mb;
1596         MetaElem *ml;
1597         float size, totsize, obinv[4][4], obmat[4][4], vec[3];
1598         //float max=0.0;
1599         int a, obnr, zero_size=0;
1600         char obname[32];
1601         
1602         copy_m4_m4(obmat, ob->obmat);   /* to cope with duplicators from next_object */
1603         invert_m4_m4(obinv, ob->obmat);
1604         a= 0;
1605         
1606         BLI_split_name_num(obname, &obnr, ob->id.name+2, '.');
1607         
1608         /* make main array */
1609         next_object(&sce_iter, 0, NULL, NULL);
1610         while(next_object(&sce_iter, 1, &base, &bob)) {
1611
1612                 if(bob->type==OB_MBALL) {
1613                         zero_size= 0;
1614                         ml= NULL;
1615
1616                         if(bob==ob && (base->flag & OB_FROMDUPLI)==0) {
1617                                 mb= ob->data;
1618         
1619                                 if(mb->editelems) ml= mb->editelems->first;
1620                                 else ml= mb->elems.first;
1621                         }
1622                         else {
1623                                 char name[32];
1624                                 int nr;
1625                                 
1626                                 BLI_split_name_num(name, &nr, bob->id.name+2, '.');
1627                                 if( strcmp(obname, name)==0 ) {
1628                                         mb= bob->data;
1629                                         
1630                                         if(mb->editelems) ml= mb->editelems->first;
1631                                         else ml= mb->elems.first;
1632                                 }
1633                         }
1634
1635                         /* when metaball object has zero scale, then MetaElem to this MetaBall
1636                          * will not be put to mainb array */
1637                         if(bob->size[0]==0.0f || bob->size[1]==0.0f || bob->size[2]==0.0f) {
1638                                 zero_size= 1;
1639                         }
1640                         else if(bob->parent) {
1641                                 struct Object *pob=bob->parent;
1642                                 while(pob) {
1643                                         if(pob->size[0]==0.0f || pob->size[1]==0.0f || pob->size[2]==0.0f) {
1644                                                 zero_size= 1;
1645                                                 break;
1646                                         }
1647                                         pob= pob->parent;
1648                                 }
1649                         }
1650
1651                         if (zero_size) {
1652                                 unsigned int ml_count=0;
1653                                 while(ml) {
1654                                         ml_count++;
1655                                         ml= ml->next;
1656                                 }
1657                                 totelem -= ml_count;
1658                         }
1659                         else {
1660                         while(ml) {
1661                                 if(!(ml->flag & MB_HIDE)) {
1662                                         int i;
1663                                         float temp1[4][4], temp2[4][4], temp3[4][4];
1664                                         float (*mat)[4] = NULL, (*imat)[4] = NULL;
1665                                         float max_x, max_y, max_z, min_x, min_y, min_z;
1666
1667                                         max_x = max_y = max_z = -3.4e38;
1668                                         min_x = min_y = min_z =  3.4e38;
1669
1670                                         /* too big stiffness seems only ugly due to linear interpolation
1671                                          * no need to have possibility for too big stiffness */
1672                                         if(ml->s > 10.0f) ml->s = 10.0f;
1673                                         
1674                                         /* Rotation of MetaElem is stored in quat */
1675                                          quat_to_mat4( temp3,ml->quat);
1676
1677                                         /* Translation of MetaElem */
1678                                         unit_m4(temp2);
1679                                         temp2[3][0]= ml->x;
1680                                         temp2[3][1]= ml->y;
1681                                         temp2[3][2]= ml->z;
1682
1683                                         mul_m4_m4m4(temp1, temp3, temp2);
1684                                 
1685                                         /* make a copy because of duplicates */
1686                                         mainb[a]= new_pgn_element(sizeof(MetaElem));
1687                                         *(mainb[a])= *ml;
1688                                         mainb[a]->bb = new_pgn_element(sizeof(BoundBox));
1689                                 
1690                                         mat= new_pgn_element(4*4*sizeof(float));
1691                                         imat= new_pgn_element(4*4*sizeof(float));
1692                                         
1693                                         /* mat is the matrix to transform from mball into the basis-mball */
1694                                         invert_m4_m4(obinv, obmat);
1695                                         mul_m4_m4m4(temp2, bob->obmat, obinv);
1696                                         /* MetaBall transformation */
1697                                         mul_m4_m4m4(mat, temp1, temp2);
1698
1699                                         invert_m4_m4(imat,mat);                         
1700
1701                                         mainb[a]->rad2= ml->rad*ml->rad;
1702
1703                                         mainb[a]->mat= (float*) mat;
1704                                         mainb[a]->imat= (float*) imat;
1705
1706                                         /* untransformed Bounding Box of MetaElem */
1707                                         /* 0 */
1708                                         mainb[a]->bb->vec[0][0]= -ml->expx;
1709                                         mainb[a]->bb->vec[0][1]= -ml->expy;
1710                                         mainb[a]->bb->vec[0][2]= -ml->expz;
1711                                         /* 1 */
1712                                         mainb[a]->bb->vec[1][0]=  ml->expx;
1713                                         mainb[a]->bb->vec[1][1]= -ml->expy;
1714                                         mainb[a]->bb->vec[1][2]= -ml->expz;
1715                                         /* 2 */
1716                                         mainb[a]->bb->vec[2][0]=  ml->expx;
1717                                         mainb[a]->bb->vec[2][1]=  ml->expy;
1718                                         mainb[a]->bb->vec[2][2]= -ml->expz;
1719                                         /* 3 */
1720                                         mainb[a]->bb->vec[3][0]= -ml->expx;
1721                                         mainb[a]->bb->vec[3][1]=  ml->expy;
1722                                         mainb[a]->bb->vec[3][2]= -ml->expz;
1723                                         /* 4 */
1724                                         mainb[a]->bb->vec[4][0]= -ml->expx;
1725                                         mainb[a]->bb->vec[4][1]= -ml->expy;
1726                                         mainb[a]->bb->vec[4][2]=  ml->expz;
1727                                         /* 5 */
1728                                         mainb[a]->bb->vec[5][0]=  ml->expx;
1729                                         mainb[a]->bb->vec[5][1]= -ml->expy;
1730                                         mainb[a]->bb->vec[5][2]=  ml->expz;
1731                                         /* 6 */
1732                                         mainb[a]->bb->vec[6][0]=  ml->expx;
1733                                         mainb[a]->bb->vec[6][1]=  ml->expy;
1734                                         mainb[a]->bb->vec[6][2]=  ml->expz;
1735                                         /* 7 */
1736                                         mainb[a]->bb->vec[7][0]= -ml->expx;
1737                                         mainb[a]->bb->vec[7][1]=  ml->expy;
1738                                         mainb[a]->bb->vec[7][2]=  ml->expz;
1739
1740                                         /* transformation of Metalem bb */
1741                                         for(i=0; i<8; i++)
1742                                                 mul_m4_v3((float ( * )[4])mat, mainb[a]->bb->vec[i]);
1743
1744                                         /* find max and min of transformed bb */
1745                                         for(i=0; i<8; i++){
1746                                                 /* find maximums */
1747                                                 if(mainb[a]->bb->vec[i][0] > max_x) max_x = mainb[a]->bb->vec[i][0];
1748                                                 if(mainb[a]->bb->vec[i][1] > max_y) max_y = mainb[a]->bb->vec[i][1];
1749                                                 if(mainb[a]->bb->vec[i][2] > max_z) max_z = mainb[a]->bb->vec[i][2];
1750                                                 /* find  minimums */
1751                                                 if(mainb[a]->bb->vec[i][0] < min_x) min_x = mainb[a]->bb->vec[i][0];
1752                                                 if(mainb[a]->bb->vec[i][1] < min_y) min_y = mainb[a]->bb->vec[i][1];
1753                                                 if(mainb[a]->bb->vec[i][2] < min_z) min_z = mainb[a]->bb->vec[i][2];
1754                                         }
1755
1756                                         /* create "new" bb, only point 0 and 6, which are
1757                                          * neccesary for octal tree filling */
1758                                         mainb[a]->bb->vec[0][0] = min_x - ml->rad;
1759                                         mainb[a]->bb->vec[0][1] = min_y - ml->rad;
1760                                         mainb[a]->bb->vec[0][2] = min_z - ml->rad;
1761
1762                                         mainb[a]->bb->vec[6][0] = max_x + ml->rad;
1763                                         mainb[a]->bb->vec[6][1] = max_y + ml->rad;
1764                                         mainb[a]->bb->vec[6][2] = max_z + ml->rad;
1765                                         
1766                                         a++;
1767                                 }
1768                                 ml= ml->next;
1769                         }
1770                         }
1771                 }
1772         }
1773
1774         
1775         /* totsize (= 'manhattan' radius) */
1776         totsize= 0.0;
1777         for(a=0; a<totelem; a++) {
1778                 
1779                 vec[0]= mainb[a]->x + mainb[a]->rad + mainb[a]->expx;
1780                 vec[1]= mainb[a]->y + mainb[a]->rad + mainb[a]->expy;
1781                 vec[2]= mainb[a]->z + mainb[a]->rad + mainb[a]->expz;
1782
1783                 calc_mballco(mainb[a], vec);
1784         
1785                 size= (float)fabs( vec[0] );
1786                 if( size > totsize ) totsize= size;
1787                 size= (float)fabs( vec[1] );
1788                 if( size > totsize ) totsize= size;
1789                 size= (float)fabs( vec[2] );
1790                 if( size > totsize ) totsize= size;
1791
1792                 vec[0]= mainb[a]->x - mainb[a]->rad;
1793                 vec[1]= mainb[a]->y - mainb[a]->rad;
1794                 vec[2]= mainb[a]->z - mainb[a]->rad;
1795                                 
1796                 calc_mballco(mainb[a], vec);
1797         
1798                 size= (float)fabs( vec[0] );
1799                 if( size > totsize ) totsize= size;
1800                 size= (float)fabs( vec[1] );
1801                 if( size > totsize ) totsize= size;
1802                 size= (float)fabs( vec[2] );
1803                 if( size > totsize ) totsize= size;
1804         }
1805
1806         for(a=0; a<totelem; a++) {
1807                 thresh+= densfunc( mainb[a], 2.0f*totsize, 2.0f*totsize, 2.0f*totsize);
1808         }
1809
1810         return totsize;
1811 }
1812
1813 /* if MetaElem lies in node, then node includes MetaElem pointer (ml_p)
1814  * pointing at MetaElem (ml)
1815  */
1816 void fill_metaball_octal_node(octal_node *node, MetaElem *ml, short i)
1817 {
1818         ml_pointer *ml_p;
1819
1820         ml_p= MEM_mallocN(sizeof(ml_pointer), "ml_pointer");
1821         ml_p->ml= ml;
1822         BLI_addtail(&(node->nodes[i]->elems), ml_p);
1823         node->count++;
1824         
1825         if(ml->flag & MB_NEGATIVE) {
1826                 node->nodes[i]->neg++;
1827         }
1828         else{
1829                 node->nodes[i]->pos++;
1830         }
1831 }
1832
1833 /* Node is subdivided as is ilustrated on the following figure:
1834  * 
1835  *      +------+------+
1836  *     /      /      /|
1837  *    +------+------+ |
1838  *   /      /      /| +
1839  *  +------+------+ |/|
1840  *  |      |      | + |
1841  *  |      |      |/| +
1842  *  +------+------+ |/
1843  *  |      |      | +
1844  *  |      |      |/
1845  *  +------+------+
1846  *  
1847  */
1848 void subdivide_metaball_octal_node(octal_node *node, float size_x, float size_y, float size_z, short depth)
1849 {
1850         MetaElem *ml;
1851         ml_pointer *ml_p;
1852         float x,y,z;
1853         int a,i;
1854
1855         /* create new nodes */
1856         for(a=0;a<8;a++){
1857                 node->nodes[a]= MEM_mallocN(sizeof(octal_node),"octal_node");
1858                 for(i=0;i<8;i++)
1859                         node->nodes[a]->nodes[i]= NULL;
1860                 node->nodes[a]->parent= node;
1861                 node->nodes[a]->elems.first= NULL;
1862                 node->nodes[a]->elems.last= NULL;
1863                 node->nodes[a]->count= 0;
1864                 node->nodes[a]->neg= 0;
1865                 node->nodes[a]->pos= 0;
1866         }
1867
1868         size_x /= 2;
1869         size_y /= 2;
1870         size_z /= 2;
1871         
1872         /* center of node */
1873         node->x = x = node->x_min + size_x;
1874         node->y = y = node->y_min + size_y;
1875         node->z = z = node->z_min + size_z;
1876
1877         /* setting up of border points of new nodes */
1878         node->nodes[0]->x_min = node->x_min;
1879         node->nodes[0]->y_min = node->y_min;
1880         node->nodes[0]->z_min = node->z_min;
1881         node->nodes[0]->x = node->nodes[0]->x_min + size_x/2;
1882         node->nodes[0]->y = node->nodes[0]->y_min + size_y/2;
1883         node->nodes[0]->z = node->nodes[0]->z_min + size_z/2;
1884         
1885         node->nodes[1]->x_min = x;
1886         node->nodes[1]->y_min = node->y_min;
1887         node->nodes[1]->z_min = node->z_min;
1888         node->nodes[1]->x = node->nodes[1]->x_min + size_x/2;
1889         node->nodes[1]->y = node->nodes[1]->y_min + size_y/2;
1890         node->nodes[1]->z = node->nodes[1]->z_min + size_z/2;
1891
1892         node->nodes[2]->x_min = x;
1893         node->nodes[2]->y_min = y;
1894         node->nodes[2]->z_min = node->z_min;
1895         node->nodes[2]->x = node->nodes[2]->x_min + size_x/2;
1896         node->nodes[2]->y = node->nodes[2]->y_min + size_y/2;
1897         node->nodes[2]->z = node->nodes[2]->z_min + size_z/2;
1898
1899         node->nodes[3]->x_min = node->x_min;
1900         node->nodes[3]->y_min = y;
1901         node->nodes[3]->z_min = node->z_min;
1902         node->nodes[3]->x = node->nodes[3]->x_min + size_x/2;
1903         node->nodes[3]->y = node->nodes[3]->y_min + size_y/2;
1904         node->nodes[3]->z = node->nodes[3]->z_min + size_z/2;
1905
1906         node->nodes[4]->x_min = node->x_min;
1907         node->nodes[4]->y_min = node->y_min;
1908         node->nodes[4]->z_min = z;
1909         node->nodes[4]->x = node->nodes[4]->x_min + size_x/2;
1910         node->nodes[4]->y = node->nodes[4]->y_min + size_y/2;
1911         node->nodes[4]->z = node->nodes[4]->z_min + size_z/2;
1912         
1913         node->nodes[5]->x_min = x;
1914         node->nodes[5]->y_min = node->y_min;
1915         node->nodes[5]->z_min = z;
1916         node->nodes[5]->x = node->nodes[5]->x_min + size_x/2;
1917         node->nodes[5]->y = node->nodes[5]->y_min + size_y/2;
1918         node->nodes[5]->z = node->nodes[5]->z_min + size_z/2;
1919
1920         node->nodes[6]->x_min = x;
1921         node->nodes[6]->y_min = y;
1922         node->nodes[6]->z_min = z;
1923         node->nodes[6]->x = node->nodes[6]->x_min + size_x/2;
1924         node->nodes[6]->y = node->nodes[6]->y_min + size_y/2;
1925         node->nodes[6]->z = node->nodes[6]->z_min + size_z/2;
1926
1927         node->nodes[7]->x_min = node->x_min;
1928         node->nodes[7]->y_min = y;
1929         node->nodes[7]->z_min = z;
1930         node->nodes[7]->x = node->nodes[7]->x_min + size_x/2;
1931         node->nodes[7]->y = node->nodes[7]->y_min + size_y/2;
1932         node->nodes[7]->z = node->nodes[7]->z_min + size_z/2;
1933
1934         ml_p= node->elems.first;
1935         
1936         /* setting up references of MetaElems for new nodes */
1937         while(ml_p){
1938                 ml= ml_p->ml;
1939                 if(ml->bb->vec[0][2] < z){
1940                         if(ml->bb->vec[0][1] < y){
1941                                 /* vec[0][0] lies in first octant */
1942                                 if(ml->bb->vec[0][0] < x){
1943                                         /* ml belongs to the (0)1st node */
1944                                         fill_metaball_octal_node(node, ml, 0);
1945
1946                                         /* ml belongs to the (3)4th node */
1947                                         if(ml->bb->vec[6][1] >= y){
1948                                                 fill_metaball_octal_node(node, ml, 3);
1949
1950                                                 /* ml belongs to the (7)8th node */
1951                                                 if(ml->bb->vec[6][2] >= z){
1952                                                         fill_metaball_octal_node(node, ml, 7);
1953                                                 }
1954                                         }
1955         
1956                                         /* ml belongs to the (1)2nd node */
1957                                         if(ml->bb->vec[6][0] >= x){
1958                                                 fill_metaball_octal_node(node, ml, 1);
1959
1960                                                 /* ml belongs to the (5)6th node */
1961                                                 if(ml->bb->vec[6][2] >= z){
1962                                                         fill_metaball_octal_node(node, ml, 5);
1963                                                 }
1964                                         }
1965
1966                                         /* ml belongs to the (2)3th node */
1967                                         if((ml->bb->vec[6][0] >= x) && (ml->bb->vec[6][1] >= y)){
1968                                                 fill_metaball_octal_node(node, ml, 2);
1969                                                 
1970                                                 /* ml belong to the (6)7th node */
1971                                                 if(ml->bb->vec[6][2] >= z){
1972                                                         fill_metaball_octal_node(node, ml, 6);
1973                                                 }
1974                                                 
1975                                         }
1976                         
1977                                         /* ml belongs to the (4)5th node too */ 
1978                                         if(ml->bb->vec[6][2] >= z){
1979                                                 fill_metaball_octal_node(node, ml, 4);
1980                                         }
1981
1982                                         
1983                                         
1984                                 }
1985                                 /* vec[0][0] is in the (1)second octant */
1986                                 else{
1987                                         /* ml belong to the (1)2nd node */
1988                                         fill_metaball_octal_node(node, ml, 1);
1989
1990                                         /* ml belongs to the (2)3th node */
1991                                         if(ml->bb->vec[6][1] >= y){
1992                                                 fill_metaball_octal_node(node, ml, 2);
1993
1994                                                 /* ml belongs to the (6)7th node */
1995                                                 if(ml->bb->vec[6][2] >= z){
1996                                                         fill_metaball_octal_node(node, ml, 6);
1997                                                 }
1998                                                 
1999                                         }
2000                                         
2001                                         /* ml belongs to the (5)6th node */
2002                                         if(ml->bb->vec[6][2] >= z){
2003                                                 fill_metaball_octal_node(node, ml, 5);
2004                                         }
2005                                 }
2006                         }
2007                         else{
2008                                 /* vec[0][0] is in the (3)4th octant */
2009                                 if(ml->bb->vec[0][0] < x){
2010                                         /* ml belongs to the (3)4nd node */
2011                                         fill_metaball_octal_node(node, ml, 3);
2012                                         
2013                                         /* ml belongs to the (7)8th node */
2014                                         if(ml->bb->vec[6][2] >= z){
2015                                                 fill_metaball_octal_node(node, ml, 7);
2016                                         }
2017                                 
2018
2019                                         /* ml belongs to the (2)3th node */
2020                                         if(ml->bb->vec[6][0] >= x){
2021                                                 fill_metaball_octal_node(node, ml, 2);
2022                                         
2023                                                 /* ml belongs to the (6)7th node */
2024                                                 if(ml->bb->vec[6][2] >= z){
2025                                                         fill_metaball_octal_node(node, ml, 6);
2026                                                 }
2027                                         }
2028                                 }
2029
2030                         }
2031
2032                         /* vec[0][0] is in the (2)3th octant */
2033                         if((ml->bb->vec[0][0] >= x) && (ml->bb->vec[0][1] >= y)){
2034                                 /* ml belongs to the (2)3th node */
2035                                 fill_metaball_octal_node(node, ml, 2);
2036                                 
2037                                 /* ml belongs to the (6)7th node */
2038                                 if(ml->bb->vec[6][2] >= z){
2039                                         fill_metaball_octal_node(node, ml, 6);
2040                                 }
2041                         }
2042                 }
2043                 else{
2044                         if(ml->bb->vec[0][1] < y){
2045                                 /* vec[0][0] lies in (4)5th octant */
2046                                 if(ml->bb->vec[0][0] < x){
2047                                         /* ml belongs to the (4)5th node */
2048                                         fill_metaball_octal_node(node, ml, 4);
2049
2050                                         if(ml->bb->vec[6][0] >= x){
2051                                                 fill_metaball_octal_node(node, ml, 5);
2052                                         }
2053
2054                                         if(ml->bb->vec[6][1] >= y){
2055                                                 fill_metaball_octal_node(node, ml, 7);
2056                                         }
2057                                         
2058                                         if((ml->bb->vec[6][0] >= x) && (ml->bb->vec[6][1] >= y)){
2059                                                 fill_metaball_octal_node(node, ml, 6);
2060                                         }
2061                                 }
2062                                 /* vec[0][0] lies in (5)6th octant */
2063                                 else{
2064                                         fill_metaball_octal_node(node, ml, 5);
2065
2066                                         if(ml->bb->vec[6][1] >= y){
2067                                                 fill_metaball_octal_node(node, ml, 6);
2068                                         }
2069                                 }
2070                         }
2071                         else{
2072                                 /* vec[0][0] lies in (7)8th octant */
2073                                 if(ml->bb->vec[0][0] < x){
2074                                         fill_metaball_octal_node(node, ml, 7);
2075
2076                                         if(ml->bb->vec[6][0] >= x){
2077                                                 fill_metaball_octal_node(node, ml, 6);
2078                                         }
2079                                 }
2080
2081                         }
2082                         
2083                         /* vec[0][0] lies in (6)7th octant */
2084                         if((ml->bb->vec[0][0] >= x) && (ml->bb->vec[0][1] >= y)){
2085                                 fill_metaball_octal_node(node, ml, 6);
2086                         }
2087                 }
2088                 ml_p= ml_p->next;
2089         }
2090
2091         /* free references of MetaElems for curent node (it is not needed anymore) */
2092         BLI_freelistN(&node->elems);
2093
2094         depth--;
2095         
2096         if(depth>0){
2097                 for(a=0;a<8;a++){
2098                         if(node->nodes[a]->count > 0) /* if node is not empty, then it is subdivided */
2099                                 subdivide_metaball_octal_node(node->nodes[a], size_x, size_y, size_z, depth);
2100                 }
2101         }
2102 }
2103
2104 /* free all octal nodes recursively */
2105 void free_metaball_octal_node(octal_node *node)
2106 {
2107         int a;
2108         for(a=0;a<8;a++){
2109                 if(node->nodes[a]!=NULL) free_metaball_octal_node(node->nodes[a]);
2110         }
2111         BLI_freelistN(&node->elems);
2112         MEM_freeN(node);
2113 }
2114
2115 /* If scene include more then one MetaElem, then octree is used */
2116 void init_metaball_octal_tree(int depth)
2117 {
2118         struct octal_node *node;
2119         ml_pointer *ml_p;
2120         float size[3];
2121         int a;
2122         
2123         metaball_tree= MEM_mallocN(sizeof(octal_tree), "metaball_octal_tree");
2124         metaball_tree->first= node= MEM_mallocN(sizeof(octal_node), "metaball_octal_node");
2125         /* maximal depth of octree */
2126         metaball_tree->depth= depth;
2127
2128         metaball_tree->neg= node->neg=0;
2129         metaball_tree->pos= node->pos=0;
2130         
2131         node->elems.first= NULL;
2132         node->elems.last= NULL;
2133         node->count=0;
2134
2135         for(a=0;a<8;a++)
2136                 node->nodes[a]=NULL;
2137
2138         node->x_min= node->y_min= node->z_min= FLT_MAX;
2139         node->x_max= node->y_max= node->z_max= -FLT_MAX;
2140
2141         /* size of octal tree scene */
2142         for(a=0;a<totelem;a++) {
2143                 if(mainb[a]->bb->vec[0][0] < node->x_min) node->x_min= mainb[a]->bb->vec[0][0];
2144                 if(mainb[a]->bb->vec[0][1] < node->y_min) node->y_min= mainb[a]->bb->vec[0][1];
2145                 if(mainb[a]->bb->vec[0][2] < node->z_min) node->z_min= mainb[a]->bb->vec[0][2];
2146                 
2147                 if(mainb[a]->bb->vec[6][0] > node->x_max) node->x_max= mainb[a]->bb->vec[6][0];
2148                 if(mainb[a]->bb->vec[6][1] > node->y_max) node->y_max= mainb[a]->bb->vec[6][1];
2149                 if(mainb[a]->bb->vec[6][2] > node->z_max) node->z_max= mainb[a]->bb->vec[6][2];
2150
2151                 ml_p= MEM_mallocN(sizeof(ml_pointer), "ml_pointer");
2152                 ml_p->ml= mainb[a];
2153                 BLI_addtail(&node->elems, ml_p);
2154
2155                 if(mainb[a]->flag & MB_NEGATIVE) {
2156                         /* number of negative MetaElem in scene */
2157                         metaball_tree->neg++;
2158                 }
2159                 else{
2160                         /* number of positive MetaElem in scene */
2161                         metaball_tree->pos++;
2162                 }
2163         }
2164
2165         /* size of first node */        
2166         size[0]= node->x_max - node->x_min;
2167         size[1]= node->y_max - node->y_min;
2168         size[2]= node->z_max - node->z_min;
2169
2170         /* first node is subdivided recursively */
2171         subdivide_metaball_octal_node(node, size[0], size[1], size[2], metaball_tree->depth);
2172 }
2173
2174 void metaball_polygonize(Scene *scene, Object *ob, ListBase *dispbase)
2175 {
2176         PROCESS mbproc;
2177         MetaBall *mb;
2178         DispList *dl;
2179         int a, nr_cubes;
2180         float *ve, *no, totsize, width;
2181
2182         mb= ob->data;
2183
2184         if(totelem==0) return;
2185         if(!(G.rendering) && (mb->flag==MB_UPDATE_NEVER)) return;
2186         if(G.moving && mb->flag==MB_UPDATE_FAST) return;
2187
2188         curindex= totindex= 0;
2189         indices= NULL;
2190         thresh= mb->thresh;
2191
2192         /* total number of MetaElems (totelem) is precomputed in find_basis_mball() function */
2193         mainb= MEM_mallocN(sizeof(void *)*totelem, "mainb");
2194         
2195         /* initialize all mainb (MetaElems) */
2196         totsize= init_meta(scene, ob);
2197
2198         if(metaball_tree){
2199                 free_metaball_octal_node(metaball_tree->first);
2200                 MEM_freeN(metaball_tree);
2201                 metaball_tree= NULL;
2202         }
2203
2204         /* if scene includes more then one MetaElem, then octal tree optimalisation is used */  
2205         if((totelem > 1) && (totelem <= 64)) init_metaball_octal_tree(1);
2206         if((totelem > 64) && (totelem <= 128)) init_metaball_octal_tree(2);
2207         if((totelem > 128) && (totelem <= 512)) init_metaball_octal_tree(3);
2208         if((totelem > 512) && (totelem <= 1024)) init_metaball_octal_tree(4);
2209         if(totelem > 1024) init_metaball_octal_tree(5);
2210
2211         /* don't polygonize metaballs with too high resolution (base mball to small)
2212          * note: Eps was 0.0001f but this was giving problems for blood animation for durian, using 0.00001f */
2213         if(metaball_tree) {
2214                 if(     ob->size[0] <= 0.00001f * (metaball_tree->first->x_max - metaball_tree->first->x_min) ||
2215                         ob->size[1] <= 0.00001f * (metaball_tree->first->y_max - metaball_tree->first->y_min) ||
2216                         ob->size[2] <= 0.00001f * (metaball_tree->first->z_max - metaball_tree->first->z_min))
2217                 {
2218                         new_pgn_element(-1); /* free values created by init_meta */
2219
2220                         MEM_freeN(mainb);
2221
2222                         /* free tree */
2223                         free_metaball_octal_node(metaball_tree->first);
2224                         MEM_freeN(metaball_tree);
2225                         metaball_tree= NULL;
2226
2227                         return;
2228                 }
2229         }
2230
2231         /* width is size per polygonize cube */
2232         if(G.rendering) width= mb->rendersize;
2233         else {
2234                 width= mb->wiresize;
2235                 if(G.moving && mb->flag==MB_UPDATE_HALFRES) width*= 2;
2236         }
2237         /* nr_cubes is just for safety, minimum is totsize */
2238         nr_cubes= (int)(0.5f+totsize/width);
2239
2240         /* init process */
2241         mbproc.function = metaball;
2242         mbproc.size = width;
2243         mbproc.bounds = nr_cubes;
2244         mbproc.cubes= NULL;
2245         mbproc.delta = width/(float)(RES*RES);
2246
2247         polygonize(&mbproc, mb);
2248         
2249         MEM_freeN(mainb);
2250
2251         /* free octal tree */
2252         if(totelem > 1){
2253                 free_metaball_octal_node(metaball_tree->first);
2254                 MEM_freeN(metaball_tree);
2255                 metaball_tree= NULL;
2256         }
2257
2258         if(curindex) {
2259                 dl= MEM_callocN(sizeof(DispList), "mbaldisp");
2260                 BLI_addtail(dispbase, dl);
2261                 dl->type= DL_INDEX4;
2262                 dl->nr= mbproc.vertices.count;
2263                 dl->parts= curindex;
2264
2265                 dl->index= indices;
2266                 indices= NULL;
2267                 
2268                 a= mbproc.vertices.count;
2269                 dl->verts= ve= MEM_mallocN(sizeof(float)*3*a, "mballverts");
2270                 dl->nors= no= MEM_mallocN(sizeof(float)*3*a, "mballnors");
2271
2272                 for(a=0; a<mbproc.vertices.count; a++, no+=3, ve+=3) {
2273                         ve[0]= mbproc.vertices.ptr[a].position.x;
2274                         ve[1]= mbproc.vertices.ptr[a].position.y;
2275                         ve[2]= mbproc.vertices.ptr[a].position.z;
2276
2277                         no[0]= mbproc.vertices.ptr[a].normal.x;
2278                         no[1]= mbproc.vertices.ptr[a].normal.y;
2279                         no[2]= mbproc.vertices.ptr[a].normal.z;
2280                 }
2281         }
2282
2283         freepolygonize(&mbproc);
2284 }
2285