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