svn merge -r 15529:15649 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / intern / elbeem / intern / controlparticles.cpp
1 // --------------------------------------------------------------------------
2 //
3 // El'Beem - the visual lattice boltzmann freesurface simulator
4 // All code distributed as part of El'Beem is covered by the version 2 of the 
5 // GNU General Public License. See the file COPYING for details.  
6 //
7 // Copyright 2008 Nils Thuerey , Richard Keiser, Mark Pauly, Ulrich Ruede
8 //
9 // implementation of control particle handling
10 //
11 // --------------------------------------------------------------------------
12
13 // indicator for LBM inclusion
14 #include "ntl_geometrymodel.h"
15 #include "ntl_world.h"
16 #include "solver_class.h"
17 #include "controlparticles.h"
18 #include "mvmcoords.h"
19 #include <zlib.h>
20
21 #ifndef sqrtf
22 #define sqrtf sqrt
23 #endif
24
25 // brute force circle test init in initTimeArray
26 // replaced by mDebugInit
27 //#define CP_FORCECIRCLEINIT 0
28
29
30 void ControlParticles::initBlenderTest() {
31         mPartSets.clear();
32
33         ControlParticleSet cps;
34         mPartSets.push_back(cps);
35         int setCnt = mPartSets.size()-1;
36         ControlParticle p; 
37
38         // set for time zero
39         mPartSets[setCnt].time = 0.;
40
41         // add single particle 
42         p.reset();
43         p.pos = LbmVec(0.5, 0.5, -0.5);
44         mPartSets[setCnt].particles.push_back(p);
45
46         // add second set for animation
47         mPartSets.push_back(cps);
48         setCnt = mPartSets.size()-1;
49         mPartSets[setCnt].time = 0.15;
50
51         // insert new position
52         p.reset();
53         p.pos = LbmVec(-0.5, -0.5, 0.5);
54         mPartSets[setCnt].particles.push_back(p);
55
56         // applyTrafos();
57         initTime(0. , 1.);
58 }
59
60 int ControlParticles::initFromObject(ntlGeometryObjModel *model) {
61         vector<ntlTriangle> triangles;
62         vector<ntlVec3Gfx> vertices;
63         vector<ntlVec3Gfx> normals;
64         
65         /*
66         model->loadBobjModel(string(infile));
67         
68         model->setLoaded(true);
69         
70         model->setGeoInitId(gid);
71         
72         
73         printf("a animated? %d\n", model->getIsAnimated());
74         printf("b animated? %d\n", model->getMeshAnimated());
75         */
76         model->setGeoInitType(FGI_FLUID);
77         
78         model->getTriangles(mCPSTimeStart, &triangles, &vertices, &normals, 1 ); 
79         // model->applyTransformation(mCPSTimeStart, &vertices, &normals, 0, vertices.size(), true);
80         
81         // valid mesh?
82         if(triangles.size() <= 0) {
83                 return 0;
84         }
85
86         ntlRenderGlobals *glob = new ntlRenderGlobals;
87         ntlScene *genscene = new ntlScene( glob, false );
88         genscene->addGeoClass(model);
89         genscene->addGeoObject(model);
90         genscene->buildScene(0., false);
91         char treeFlag = (1<<(4+model->getGeoInitId()));
92
93         ntlTree *tree = new ntlTree( 
94         15, 8,  // TREEwarning - fixed values for depth & maxtriangles here...
95         genscene, treeFlag );
96
97         // TODO? use params
98         ntlVec3Gfx start,end;
99         model->getExtends(start,end);
100         /*
101         printf("start - x: %f, y: %f, z: %f\n", start[0], start[1], start[2]);
102         printf("end   - x: %f, y: %f, z: %f\n", end[0], end[1], end[2]);
103         printf("mCPSWidth: %f\n");
104 */
105         LbmFloat width = mCPSWidth;
106         if(width<=LBM_EPSILON) { errMsg("ControlParticles::initFromMVMCMesh","Invalid mCPSWidth! "<<mCPSWidth); width=mCPSWidth=0.1; }
107         ntlVec3Gfx org = start+ntlVec3Gfx(width*0.5);
108         gfxReal distance = -1.;
109         vector<ntlVec3Gfx> inspos;
110         int approxmax = (int)( ((end[0]-start[0])/width)*((end[1]-start[1])/width)*((end[2]-start[2])/width) );
111
112         // printf("distance: %f, width: %f\n", distance, width);
113         
114         while(org[2]<end[2]) {
115                 while(org[1]<end[1]) {
116                         while(org[0]<end[0]) {
117                                 if(checkPointInside(tree, org, distance)) {
118                                         inspos.push_back(org);
119                                 }
120                                 // TODO optimize, use distance
121                                 org[0] += width;
122                         }
123                         org[1] += width;
124                         org[0] = start[0];
125                 }
126                 org[2] += width;
127                 org[1] = start[1];
128         }
129         
130         // printf("inspos.size(): %d\n", inspos.size());
131
132         MeanValueMeshCoords mvm;
133         mvm.calculateMVMCs(vertices,triangles, inspos, mCPSWeightFac);
134         vector<ntlVec3Gfx> ninspos;
135         mvm.transfer(vertices, ninspos);
136
137         // init first set, check dist
138         ControlParticleSet firstcps; //T
139         mPartSets.push_back(firstcps);
140         mPartSets[mPartSets.size()-1].time = (gfxReal)0.;
141         vector<bool> useCP;
142
143         for(int i=0; i<(int)inspos.size(); i++) {
144                 ControlParticle p; p.reset();
145                 p.pos = vec2L(inspos[i]);
146                 
147                 double cpdist = norm(inspos[i]-ninspos[i]);
148                 bool usecpv = true;
149
150                 mPartSets[mPartSets.size()-1].particles.push_back(p);
151                 useCP.push_back(usecpv);
152         }
153
154         // init further sets, temporal mesh sampling
155         double tsampling = mCPSTimestep;
156         // printf("tsampling: %f, ninspos.size(): %d, mCPSTimeEnd: %f\n", tsampling, ninspos.size(), mCPSTimeEnd);
157         
158         int totcnt = (int)( (mCPSTimeEnd-mCPSTimeStart)/tsampling ), tcnt=0;
159         for(double t=mCPSTimeStart+tsampling; ((t<mCPSTimeEnd) && (ninspos.size()>0.)); t+=tsampling) {
160                 ControlParticleSet nextcps; //T
161                 mPartSets.push_back(nextcps);
162                 mPartSets[mPartSets.size()-1].time = (gfxReal)t;
163
164                 vertices.clear(); triangles.clear(); normals.clear();
165                 model->getTriangles(t, &triangles, &vertices, &normals, 1 );
166                 mvm.transfer(vertices, ninspos);
167                 
168                 tcnt++;
169                 for(int i=0; i<(int)ninspos.size(); i++) {
170                         
171                         if(useCP[i]) {
172                                 ControlParticle p; p.reset();
173                                 p.pos = vec2L(ninspos[i]);
174                                 mPartSets[mPartSets.size()-1].particles.push_back(p);
175                         }
176                 }
177         }
178         
179         model->setGeoInitType(FGI_CONTROL);
180
181         delete tree;
182         delete genscene;
183         delete glob;
184         
185         return 1;
186 }
187
188
189 // init all zero / defaults for a single particle
190 void ControlParticle::reset() {
191         pos = LbmVec(0.,0.,0.);
192         vel = LbmVec(0.,0.,0.);
193         influence = 1.;
194         size = 1.;
195 #ifndef LBMDIM
196 #ifdef MAIN_2D
197         rotaxis = LbmVec(0.,1.,0.); // SPH xz
198 #else // MAIN_2D
199         // 3d - roate in xy plane, vortex
200         rotaxis = LbmVec(0.,0.,1.);
201         // 3d - rotate for wave
202         //rotaxis = LbmVec(0.,1.,0.);
203 #endif // MAIN_2D
204 #else // LBMDIM
205         rotaxis = LbmVec(0.,1.,0.); // LBM xy , is swapped afterwards
206 #endif // LBMDIM
207
208         density = 0.;
209         densityWeight = 0.;
210         avgVelAcc = avgVel = LbmVec(0.);
211         avgVelWeight = 0.;
212 }
213
214
215 // default preset/empty init
216 ControlParticles::ControlParticles() :
217         _influenceTangential(0.f),
218         _influenceAttraction(0.f),
219         _influenceVelocity(0.f),
220         _influenceMaxdist(0.f),
221         _radiusAtt(1.0f),
222         _radiusVel(1.0f),
223         _radiusMinMaxd(2.0f),
224         _radiusMaxd(3.0f),
225         _currTime(-1.0), _currTimestep(1.),
226         _initTimeScale(1.), 
227         _initPartOffset(0.), _initPartScale(1.),
228         _initLastPartOffset(0.), _initLastPartScale(1.),
229         _initMirror(""),
230         _fluidSpacing(1.), _kernelWeight(-1.),
231         _charLength(1.), _charLengthInv(1.),
232         mvCPSStart(-10000.), mvCPSEnd(10000.),
233         mCPSWidth(0.1), mCPSTimestep(0.05),
234         mCPSTimeStart(0.), mCPSTimeEnd(0.5), mCPSWeightFac(1.),
235         mDebugInit(0)
236 {
237         _radiusAtt = 0.15f;
238         _radiusVel = 0.15f;
239         _radiusMinMaxd = 0.16f;
240         _radiusMaxd = 0.3;
241
242         _influenceAttraction = 0.f;
243         _influenceTangential = 0.f;
244         _influenceVelocity = 0.f;
245         // 3d tests */
246 }
247
248
249  
250 ControlParticles::~ControlParticles() {
251         // nothing to do...
252 }
253
254 LbmFloat ControlParticles::getControlTimStart() {
255         if(mPartSets.size()>0) { return mPartSets[0].time; }
256         return -1000.;
257 }
258 LbmFloat ControlParticles::getControlTimEnd() {
259         if(mPartSets.size()>0) { return mPartSets[mPartSets.size()-1].time; }
260         return -1000.;
261 }
262
263 // calculate for delta t
264 void ControlParticles::setInfluenceVelocity(LbmFloat set, LbmFloat dt) {
265         const LbmFloat dtInter = 0.01;
266         LbmFloat facFv = 1.-set; //cparts->getInfluenceVelocity();
267         // mLevel[mMaxRefine].timestep
268         LbmFloat facNv = (LbmFloat)( 1.-pow( (double)facFv, (double)(dt/dtInter)) );
269         //errMsg("vwcalc","ts:"<<dt<< " its:"<<(dt/dtInter) <<" fv"<<facFv<<" nv"<<facNv<<" test:"<< pow( (double)(1.-facNv),(double)(dtInter/dt))      );
270         _influenceVelocity = facNv;
271 }
272
273 int ControlParticles::initExampleSet()
274 {
275         // unused
276 }
277
278 int ControlParticles::getTotalSize()
279 {
280         int s=0;
281         for(int i=0; i<(int)mPartSets.size(); i++) {
282                 s+= mPartSets[i].particles.size();
283         }
284         return s;
285 }
286
287 // --------------------------------------------------------------------------
288 // load positions & timing from text file
289 // WARNING - make sure file has unix format, no win/dos linefeeds...
290 #define LINE_LEN 100
291 int ControlParticles::initFromTextFile(string filename)
292 {
293         const bool debugRead = false;
294         char line[LINE_LEN];
295         line[LINE_LEN-1] = '\0';
296         mPartSets.clear();
297         if(filename.size()<2) return 0;
298
299         // HACK , use "cparts" suffix as old
300         // e.g. "cpart2" as new
301         if(filename[ filename.size()-1 ]=='s') {
302                 return initFromTextFileOld(filename);
303         }
304
305         FILE *infile = fopen(filename.c_str(), "r");
306         if(!infile) {
307                 errMsg("ControlParticles::initFromTextFile","unable to open '"<<filename<<"' " );
308                 // try to open as gz sequence
309                 if(initFromBinaryFile(filename)) { return 1; }
310                 // try mesh MVCM generation
311                 if(initFromMVCMesh(filename)) { return 1; }
312                 // failed...
313                 return 0;
314         }
315
316         int haveNo = false;
317         int haveScale = false;
318         int haveTime = false;
319         int noParts = -1;
320         int partCnt = 0;
321         int setCnt = 0;
322         //ControlParticle p; p.reset();
323         // scale times by constant factor while reading
324         LbmFloat timeScale= 1.0;
325         int lineCnt = 0;
326         bool abortParse = false;
327 #define LASTCP mPartSets[setCnt].particles[ mPartSets[setCnt].particles.size()-1 ]
328
329         while( (!feof(infile)) && (!abortParse)) {
330                 lineCnt++;
331                 fgets(line, LINE_LEN, infile);
332
333                 //if(debugRead) printf("\nDEBUG%d r '%s'\n",lineCnt, line);
334                 if(!line) continue;
335                 int len = (int)strlen(line);
336
337                 // skip empty lines and comments (#,//)
338                 if(len<1) continue;
339                 if( (line[0]=='#') || (line[0]=='\n') ) continue;
340                 if((len>1) && (line[0]=='/' && line[1]=='/')) continue;
341
342                 // debug remove newline
343                 if((len>=1)&&(line[len-1]=='\n')) line[len-1]='\0';
344
345                 switch(line[0]) {
346
347                 case 'N': { // total number of particles, more for debugging...
348                         noParts = atoi(line+2);
349                         if(noParts<=0) {
350                                 errMsg("ControlParticles::initFromTextFile","file '"<<filename<<"' - invalid no of particles "<<noParts);
351                                 mPartSets.clear(); fclose(infile); return 0;
352                         }
353                         if(debugRead) printf("CPDEBUG%d no parts '%d'\n",lineCnt, noParts );
354                         haveNo = true;
355                         } break;
356
357                 case 'T': { // global time scale
358                         timeScale *= (LbmFloat)atof(line+2);
359                         if(debugRead) printf("ControlParticles::initFromTextFile - line %d , set timescale '%f', org %f\n",lineCnt, timeScale , _initTimeScale);
360                         if(timeScale==0.) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error: timescale = 0.! reseting to 1 ...\n",lineCnt); timeScale=1.; }
361                         haveScale = true;
362                         } break;
363
364                 case 'I': { // influence settings, overrides others as of now...
365                         float val = (LbmFloat)atof(line+3);
366                         const char *setvar = "[invalid]";
367                         switch(line[1]) {
368                                 //case 'f': { _influenceFalloff = val; setvar = "falloff"; } break;
369                                 case 't': { _influenceTangential = val; setvar = "tangential"; } break;
370                                 case 'a': { _influenceAttraction = val; setvar = "attraction"; } break;
371                                 case 'v': { _influenceVelocity = val; setvar = "velocity"; } break;
372                                 case 'm': { _influenceMaxdist = val; setvar = "maxdist"; } break;
373                                 default: 
374                                         fprintf(stdout,"ControlParticles::initFromTextFile (%s) - line %d , invalid influence setting %c, %f\n",filename.c_str() ,lineCnt, line[1], val);
375                         }
376                         if(debugRead) printf("CPDEBUG%d set influence '%s'=%f \n",lineCnt, setvar, val);
377                         } break;
378
379                 case 'R': { // radius settings, overrides others as of now...
380                         float val = (LbmFloat)atof(line+3);
381                         const char *setvar = "[invalid]";
382                         switch(line[1]) {
383                                 case 'a': { _radiusAtt = val; setvar = "r_attraction"; } break;
384                                 case 'v': { _radiusVel = val; setvar = "r_velocity"; } break;
385                                 case 'm': { _radiusMaxd = val; setvar = "r_maxdist"; } break;
386                                 default: 
387                                         fprintf(stdout,"ControlParticles::initFromTextFile (%s) - line %d , invalid influence setting %c, %f\n",filename.c_str() ,lineCnt, line[1], val);
388                         }
389                         if(debugRead) printf("CPDEBUG%d set influence '%s'=%f \n",lineCnt, setvar, val);
390                         } break;
391
392                 case 'S': { // new particle set at time T
393                         ControlParticleSet cps;
394                         mPartSets.push_back(cps);
395                         setCnt = (int)mPartSets.size()-1;
396
397                         LbmFloat val = (LbmFloat)atof(line+2);
398                         mPartSets[setCnt].time = val * timeScale;
399                         if(debugRead) printf("CPDEBUG%d new set, time '%f', %d\n",lineCnt, mPartSets[setCnt].time, setCnt );
400                         haveTime = true;
401                         partCnt = -1;
402                         } break;
403
404                 case 'P':   // new particle with pos
405                 case 'n': { // new particle without pos
406                                 if((!haveTime)||(setCnt<0)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error: set missing!\n",lineCnt); abortParse=true; break; }
407                                 partCnt++;
408                                 if(partCnt>=noParts) {
409                                         if(debugRead) printf("CPDEBUG%d partset done \n",lineCnt);
410                                         haveTime = false;
411                                 } else {
412                                         ControlParticle p; p.reset();
413                                         mPartSets[setCnt].particles.push_back(p);
414                                 }
415                         } 
416                         // only new part, or new with pos?
417                         if(line[0] == 'n') break;
418
419                 // particle properties
420
421                 case 'p': { // new particle set at time T
422                         if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|p: particle missing!\n",lineCnt); abortParse=true; break; }
423                         float px=0.,py=0.,pz=0.;
424                         if( sscanf(line+2,"%f %f %f",&px,&py,&pz) != 3) {
425                                 fprintf(stdout,"CPDEBUG%d, unable to parse position!\n",lineCnt); abortParse=true; break; 
426                         }
427                         if(!(finite(px)&&finite(py)&&finite(pz))) { px=py=pz=0.; }
428                         LASTCP.pos[0] = px;
429                         LASTCP.pos[1] = py;
430                         LASTCP.pos[2] = pz; 
431                         if(debugRead) printf("CPDEBUG%d part%d,%d: position %f,%f,%f \n",lineCnt,setCnt,partCnt, px,py,pz);
432                         } break;
433
434                 case 's': { // particle size
435                         if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|s: particle missing!\n",lineCnt); abortParse=true; break; }
436                         float ps=1.;
437                         if( sscanf(line+2,"%f",&ps) != 1) {
438                                 fprintf(stdout,"CPDEBUG%d, unable to parse size!\n",lineCnt); abortParse=true; break; 
439                         }
440                         if(!(finite(ps))) { ps=0.; }
441                         LASTCP.size = ps;
442                         if(debugRead) printf("CPDEBUG%d part%d,%d: size %f \n",lineCnt,setCnt,partCnt, ps);
443                         } break;
444
445                 case 'i': { // particle influence
446                         if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|i: particle missing!\n",lineCnt); abortParse=true; break; }
447                         float pinf=1.;
448                         if( sscanf(line+2,"%f",&pinf) != 1) {
449                                 fprintf(stdout,"CPDEBUG%d, unable to parse size!\n",lineCnt); abortParse=true; break; 
450                         }
451                         if(!(finite(pinf))) { pinf=0.; }
452                         LASTCP.influence = pinf;
453                         if(debugRead) printf("CPDEBUG%d part%d,%d: influence %f \n",lineCnt,setCnt,partCnt, pinf);
454                         } break;
455
456                 case 'a': { // rotation axis
457                         if((!haveTime)||(setCnt<0)||(mPartSets[setCnt].particles.size()<1)) { fprintf(stdout,"ControlParticles::initFromTextFile - line %d ,error|a: particle missing!\n",lineCnt); abortParse=true; break; }
458                         float px=0.,py=0.,pz=0.;
459                         if( sscanf(line+2,"%f %f %f",&px,&py,&pz) != 3) {
460                                 fprintf(stdout,"CPDEBUG%d, unable to parse rotaxis!\n",lineCnt); abortParse=true; break; 
461                         }
462                         if(!(finite(px)&&finite(py)&&finite(pz))) { px=py=pz=0.; }
463                         LASTCP.rotaxis[0] = px;
464                         LASTCP.rotaxis[1] = py;
465                         LASTCP.rotaxis[2] = pz; 
466                         if(debugRead) printf("CPDEBUG%d part%d,%d: rotaxis %f,%f,%f \n",lineCnt,setCnt,partCnt, px,py,pz);
467                         } break;
468
469
470                 default:
471                         if(debugRead) printf("CPDEBUG%d ignored: '%s'\n",lineCnt, line );
472                         break;
473                 }
474         }
475         if(debugRead && abortParse) printf("CPDEBUG aborted parsing after set... %d\n",(int)mPartSets.size() );
476
477         // sanity check
478         for(int i=0; i<(int)mPartSets.size(); i++) {
479                 if( (int)mPartSets[i].particles.size()!=noParts) {
480                         fprintf(stdout,"ControlParticles::initFromTextFile (%s) - invalid no of particles in set %d, is:%d, shouldbe:%d \n",filename.c_str() ,i,(int)mPartSets[i].particles.size(), noParts);
481                         mPartSets.clear();
482                         fclose(infile);
483                         return 0;
484                 }
485         }
486
487         // print stats
488         printf("ControlParticles::initFromTextFile (%s): Read %d sets, each %d particles\n",filename.c_str() ,
489                         (int)mPartSets.size(), noParts );
490         if(mPartSets.size()>0) {
491                 printf("ControlParticles::initFromTextFile (%s): Time: %f,%f\n",filename.c_str() ,mPartSets[0].time, mPartSets[mPartSets.size()-1].time );
492         }
493         
494         // done...
495         fclose(infile);
496         applyTrafos();
497         return 1;
498 }
499
500
501 int ControlParticles::initFromTextFileOld(string filename)
502 {
503         const bool debugRead = false;
504         char line[LINE_LEN];
505         line[LINE_LEN-1] = '\0';
506         mPartSets.clear();
507         if(filename.size()<1) return 0;
508
509         FILE *infile = fopen(filename.c_str(), "r");
510         if(!infile) {
511                 fprintf(stdout,"ControlParticles::initFromTextFileOld - unable to open '%s'\n",filename.c_str() );
512                 return 0;
513         }
514
515         int haveNo = false;
516         int haveScale = false;
517         int haveTime = false;
518         int noParts = -1;
519         int coordCnt = 0;
520         int partCnt = 0;
521         int setCnt = 0;
522         ControlParticle p; p.reset();
523         // scale times by constant factor while reading
524         LbmFloat timeScale= 1.0;
525         int lineCnt = 0;
526
527         while(!feof(infile)) {
528                 lineCnt++;
529                 fgets(line, LINE_LEN, infile);
530
531                 if(debugRead) printf("\nDEBUG%d r '%s'\n",lineCnt, line);
532
533                 if(!line) continue;
534                 int len = (int)strlen(line);
535
536                 // skip empty lines and comments (#,//)
537                 if(len<1) continue;
538                 if( (line[0]=='#') || (line[0]=='\n') ) continue;
539                 if((len>1) && (line[0]=='/' && line[1]=='/')) continue;
540
541                 // debug remove newline
542                 if((len>=1)&&(line[len-1]=='\n')) line[len-1]='\0';
543
544                 // first read no. of particles
545                 if(!haveNo) {
546                         noParts = atoi(line);
547                         if(noParts<=0) {
548                                 fprintf(stdout,"ControlParticles::initFromTextFileOld - invalid no of particles %d\n",noParts);
549                                 mPartSets.clear();
550                                 fclose(infile);
551                                 return 0;
552                         }
553                         if(debugRead) printf("DEBUG%d noparts '%d'\n",lineCnt, noParts );
554                         haveNo = true;
555                 } 
556
557                 // then read time scale
558                 else if(!haveScale) {
559                         timeScale *= (LbmFloat)atof(line);
560                         if(debugRead) printf("DEBUG%d tsc '%f', org %f\n",lineCnt, timeScale , _initTimeScale);
561                         haveScale = true;
562                 } 
563
564                 // then get set time
565                 else if(!haveTime) {
566                         ControlParticleSet cps;
567                         mPartSets.push_back(cps);
568                         setCnt = (int)mPartSets.size()-1;
569
570                         LbmFloat val = (LbmFloat)atof(line);
571                         mPartSets[setCnt].time = val * timeScale;
572                         if(debugRead) printf("DEBUG%d time '%f', %d\n",lineCnt, mPartSets[setCnt].time, setCnt );
573                         haveTime = true;
574                 }
575
576                 // default read all parts
577                 else {
578                         LbmFloat val = (LbmFloat)atof(line);
579                         if(debugRead) printf("DEBUG: l%d s%d,particle%d '%f' %d,%d/%d\n",lineCnt,(int)mPartSets.size(),(int)mPartSets[setCnt].particles.size(), val ,coordCnt,partCnt,noParts);
580                         p.pos[coordCnt] = val;
581                         coordCnt++;
582                         if(coordCnt>=3) {
583                                 mPartSets[setCnt].particles.push_back(p);
584                                 p.reset();
585                                 coordCnt=0;
586                                 partCnt++;
587                         }
588                         if(partCnt>=noParts) {
589                                 partCnt = 0;
590                                 haveTime = false;
591                         }
592                         //if(debugRead) printf("DEBUG%d par2 %d,%d/%d\n",lineCnt, coordCnt,partCnt,noParts);
593                 }
594                 //read pos, vel ...
595         }
596
597         // sanity check
598         for(int i=0; i<(int)mPartSets.size(); i++) {
599                 if( (int)mPartSets[i].particles.size()!=noParts) {
600                         fprintf(stdout,"ControlParticles::initFromTextFileOld - invalid no of particles in set %d, is:%d, shouldbe:%d \n",i,(int)mPartSets[i].particles.size(), noParts);
601                         mPartSets.clear();
602                         fclose(infile);
603                         return 0;
604                 }
605         }
606         // print stats
607         printf("ControlParticles::initFromTextFileOld: Read %d sets, each %d particles\n",
608                         (int)mPartSets.size(), noParts );
609         if(mPartSets.size()>0) {
610                 printf("ControlParticles::initFromTextFileOld: Time: %f,%f\n",mPartSets[0].time, mPartSets[mPartSets.size()-1].time );
611         }
612         
613         // done...
614         fclose(infile);
615         applyTrafos();
616         return 1;
617 }
618
619 // load positions & timing from gzipped binary file
620 int ControlParticles::initFromBinaryFile(string filename) {
621         mPartSets.clear();
622         if(filename.size()<1) return 0;
623         int fileNotFound=0;
624         int fileFound=0;
625         char ofile[256];
626
627         for(int set=0; ((set<10000)&&(fileNotFound<10)); set++) {
628                 snprintf(ofile,256,"%s%04d.gz",filename.c_str(),set);
629                 //errMsg("ControlParticle::initFromBinaryFile","set"<<set<<" notf"<<fileNotFound<<" ff"<<fileFound);
630
631                 gzFile gzf;
632                 gzf = gzopen(ofile, "rb");
633                 if (!gzf) {
634                         //errMsg("ControlParticles::initFromBinaryFile","Unable to open file for reading '"<<ofile<<"' "); 
635                         fileNotFound++;
636                         continue;
637                 }
638                 fileNotFound=0;
639                 fileFound++;
640
641                 ControlParticleSet cps;
642                 mPartSets.push_back(cps);
643                 int setCnt = (int)mPartSets.size()-1;
644                 //LbmFloat val = (LbmFloat)atof(line+2);
645                 mPartSets[setCnt].time = (gfxReal)set;
646
647                 int totpart = 0;
648                 gzread(gzf, &totpart, sizeof(totpart));
649
650                 for(int a=0; a<totpart; a++) {
651                         int ptype=0;
652                         float psize=0.0;
653                         ntlVec3Gfx ppos,pvel;
654                         gzread(gzf, &ptype, sizeof( ptype )); 
655                         gzread(gzf, &psize, sizeof( float )); 
656
657                         for(int j=0; j<3; j++) { gzread(gzf, &ppos[j], sizeof( float )); }
658                         for(int j=0; j<3; j++) { gzread(gzf, &pvel[j], sizeof( float )); }
659
660                         ControlParticle p; 
661                         p.reset();
662                         p.pos = vec2L(ppos);
663                         mPartSets[setCnt].particles.push_back(p);
664                 } 
665
666                 gzclose(gzf);
667                 //errMsg("ControlParticle::initFromBinaryFile","Read set "<<ofile<<", #"<<mPartSets[setCnt].particles.size() ); // DEBUG
668         } // sets
669
670         if(fileFound==0) return 0;
671         applyTrafos();
672         return 1;
673 }
674
675 int globCPIProblems =0;
676 bool ControlParticles::checkPointInside(ntlTree *tree, ntlVec3Gfx org, gfxReal &distance) {
677         // warning - stripped down version of geoInitCheckPointInside
678         const int globGeoInitDebug = 0;
679         const int  flags = FGI_FLUID;
680         org += ntlVec3Gfx(0.0001);
681         ntlVec3Gfx dir = ntlVec3Gfx(1.0, 0.0, 0.0);
682         int OId = -1;
683         ntlRay ray(org, dir, 0, 1.0, NULL);
684         bool done = false;
685         bool inside = false;
686         int mGiObjInside = 0; 
687         LbmFloat mGiObjDistance = -1.0; 
688         LbmFloat giObjFirstHistSide = 0; 
689         
690         // if not inside, return distance to first hit
691         gfxReal firstHit=-1.0;
692         int     firstOId = -1;
693         if(globGeoInitDebug) errMsg("IIIstart"," isect "<<org);
694
695         while(!done) {
696                 // find first inside intersection
697                 ntlTriangle *triIns = NULL;
698                 distance = -1.0;
699                 ntlVec3Gfx normal(0.0);
700                 tree->intersectX(ray,distance,normal, triIns, flags, true);
701                 if(triIns) {
702                         ntlVec3Gfx norg = ray.getOrigin() + ray.getDirection()*distance;
703                         LbmFloat orientation = dot(normal, dir);
704                         OId = triIns->getObjectId();
705                         if(orientation<=0.0) {
706                                 // outside hit
707                                 normal *= -1.0;
708                                 mGiObjInside++;
709                                 if(giObjFirstHistSide==0) giObjFirstHistSide = 1;
710                                 if(globGeoInitDebug) errMsg("IIO"," oid:"<<OId<<" org"<<org<<" norg"<<norg<<" orient:"<<orientation);
711                         } else {
712                                 // inside hit
713                                 mGiObjInside++;
714                                 if(mGiObjDistance<0.0) mGiObjDistance = distance;
715                                 if(globGeoInitDebug) errMsg("III"," oid:"<<OId<<" org"<<org<<" norg"<<norg<<" orient:"<<orientation);
716                                 if(giObjFirstHistSide==0) giObjFirstHistSide = -1;
717                         }
718                         norg += normal * getVecEpsilon();
719                         ray = ntlRay(norg, dir, 0, 1.0, NULL);
720                         // remember first hit distance, in case we're not 
721                         // inside anything
722                         if(firstHit<0.0) {
723                                 firstHit = distance;
724                                 firstOId = OId;
725                         }
726                 } else {
727                         // no more intersections... return false
728                         done = true;
729                 }
730         }
731
732         distance = -1.0;
733         if(mGiObjInside>0) {
734                 bool mess = false;
735                 if((mGiObjInside%2)==1) {
736                         if(giObjFirstHistSide != -1) mess=true;
737                 } else {
738                         if(giObjFirstHistSide !=  1) mess=true;
739                 }
740                 if(mess) {
741                         // ?
742                         //errMsg("IIIproblem","At "<<org<<" obj  inside:"<<mGiObjInside<<" firstside:"<<giObjFirstHistSide );
743                         globCPIProblems++;
744                         mGiObjInside++; // believe first hit side...
745                 }
746         }
747
748         if(globGeoInitDebug) errMsg("CHIII"," ins="<<mGiObjInside<<" t"<<mGiObjDistance<<" d"<<distance);
749         if(((mGiObjInside%2)==1)&&(mGiObjDistance>0.0)) {
750                 if(  (distance<0.0)                             || // first intersection -> good
751                                 ((distance>0.0)&&(distance>mGiObjDistance)) // more than one intersection -> use closest one
752                         ) {                                             
753                         distance = mGiObjDistance;
754                         OId = 0;
755                         inside = true;
756                 } 
757         }
758
759         if(!inside) {
760                 distance = firstHit;
761                 OId = firstOId;
762         }
763         if(globGeoInitDebug) errMsg("CHIII","ins"<<inside<<"  fh"<<firstHit<<" fo"<<firstOId<<" - h"<<distance<<" o"<<OId);
764
765         return inside;
766 }
767 int ControlParticles::initFromMVCMesh(string filename) {
768         myTime_t mvmstart = getTime(); 
769         ntlGeometryObjModel *model = new ntlGeometryObjModel();
770         int gid=1;
771         char infile[256];
772         vector<ntlTriangle> triangles;
773         vector<ntlVec3Gfx> vertices;
774         vector<ntlVec3Gfx> normals;
775         snprintf(infile,256,"%s.bobj.gz", filename.c_str() );
776         model->loadBobjModel(string(infile));
777         model->setLoaded(true);
778         model->setGeoInitId(gid);
779         model->setGeoInitType(FGI_FLUID);
780         debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"infile:"<<string(infile) ,4);
781
782         //getTriangles(double t,  vector<ntlTriangle> *triangles, vector<ntlVec3Gfx> *vertices, vector<ntlVec3Gfx> *normals, int objectId );
783         model->getTriangles(mCPSTimeStart, &triangles, &vertices, &normals, 1 ); 
784         debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG," tris:"<<triangles.size()<<" verts:"<<vertices.size()<<" norms:"<<normals.size() , 2);
785         
786         // valid mesh?
787         if(triangles.size() <= 0) {
788                 return 0;
789         }
790
791         ntlRenderGlobals *glob = new ntlRenderGlobals;
792         ntlScene *genscene = new ntlScene( glob, false );
793         genscene->addGeoClass(model);
794         genscene->addGeoObject(model);
795         genscene->buildScene(0., false);
796         char treeFlag = (1<<(4+gid));
797
798         ntlTree *tree = new ntlTree( 
799                         15, 8,  // TREEwarning - fixed values for depth & maxtriangles here...
800                         genscene, treeFlag );
801
802         // TODO? use params
803         ntlVec3Gfx start,end;
804         model->getExtends(start,end);
805
806         LbmFloat width = mCPSWidth;
807         if(width<=LBM_EPSILON) { errMsg("ControlParticles::initFromMVMCMesh","Invalid mCPSWidth! "<<mCPSWidth); width=mCPSWidth=0.1; }
808         ntlVec3Gfx org = start+ntlVec3Gfx(width*0.5);
809         gfxReal distance = -1.;
810         vector<ntlVec3Gfx> inspos;
811         int approxmax = (int)( ((end[0]-start[0])/width)*((end[1]-start[1])/width)*((end[2]-start[2])/width) );
812
813         debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"start"<<start<<" end"<<end<<" w="<<width<<" maxp:"<<approxmax, 5);
814         while(org[2]<end[2]) {
815                 while(org[1]<end[1]) {
816                         while(org[0]<end[0]) {
817                                 if(checkPointInside(tree, org, distance)) {
818                                         inspos.push_back(org);
819                                         //inspos.push_back(org+ntlVec3Gfx(width));
820                                         //inspos.push_back(start+end*0.5);
821                                 }
822                                 // TODO optimize, use distance
823                                 org[0] += width;
824                         }
825                         org[1] += width;
826                         org[0] = start[0];
827                 }
828                 org[2] += width;
829                 org[1] = start[1];
830         }
831         debMsgStd("ControlParticles::initFromMVMCMesh",DM_MSG,"points: "<<inspos.size()<<" initproblems: "<<globCPIProblems,5 );
832
833         MeanValueMeshCoords mvm;
834         mvm.calculateMVMCs(vertices,triangles, inspos, mCPSWeightFac);
835         vector<ntlVec3Gfx> ninspos;
836         mvm.transfer(vertices, ninspos);
837
838         // init first set, check dist
839         ControlParticleSet firstcps; //T
840         mPartSets.push_back(firstcps);
841         mPartSets[mPartSets.size()-1].time = (gfxReal)0.;
842         vector<bool> useCP;
843         bool debugPos=false;
844
845         for(int i=0; i<(int)inspos.size(); i++) {
846                 ControlParticle p; p.reset();
847                 p.pos = vec2L(inspos[i]);
848                 //errMsg("COMP "," "<<inspos[i]<<" vs "<<ninspos[i] );
849                 double cpdist = norm(inspos[i]-ninspos[i]);
850                 bool usecpv = true;
851                 if(debugPos) errMsg("COMP "," "<<cpdist<<usecpv);
852
853                 mPartSets[mPartSets.size()-1].particles.push_back(p);
854                 useCP.push_back(usecpv);
855         }
856
857         // init further sets, temporal mesh sampling
858         double tsampling = mCPSTimestep;
859         int totcnt = (int)( (mCPSTimeEnd-mCPSTimeStart)/tsampling ), tcnt=0;
860         for(double t=mCPSTimeStart+tsampling; ((t<mCPSTimeEnd) && (ninspos.size()>0.)); t+=tsampling) {
861                 ControlParticleSet nextcps; //T
862                 mPartSets.push_back(nextcps);
863                 mPartSets[mPartSets.size()-1].time = (gfxReal)t;
864
865                 vertices.clear(); triangles.clear(); normals.clear();
866                 model->getTriangles(t, &triangles, &vertices, &normals, 1 );
867                 mvm.transfer(vertices, ninspos);
868                 if(tcnt%(totcnt/10)==1) debMsgStd("MeanValueMeshCoords::calculateMVMCs",DM_MSG,"Transferring animation, frame: "<<tcnt<<"/"<<totcnt,5 );
869                 tcnt++;
870                 for(int i=0; i<(int)ninspos.size(); i++) {
871                         if(debugPos) errMsg("COMP "," "<<norm(inspos[i]-ninspos[i]) );
872                         if(useCP[i]) {
873                                 ControlParticle p; p.reset();
874                                 p.pos = vec2L(ninspos[i]);
875                                 mPartSets[mPartSets.size()-1].particles.push_back(p);
876                         }
877                 }
878         }
879
880         applyTrafos();
881
882         myTime_t mvmend = getTime(); 
883         debMsgStd("ControlParticle::initFromMVMCMesh",DM_MSG,"t:"<<getTimeString(mvmend-mvmstart)<<" ",7 );
884         delete tree;
885         delete genscene;
886         delete glob;
887 //exit(1); // DEBUG
888         return 1;
889 }
890
891 #define TRISWAP(v,a,b) { LbmFloat tmp = (v)[b]; (v)[b]=(v)[a]; (v)[a]=tmp; }
892 #define TRISWAPALL(v,a,b) {  \
893                         TRISWAP( (v).pos     ,a,b ); \
894                         TRISWAP( (v).vel     ,a,b ); \
895                         TRISWAP( (v).rotaxis ,a,b ); }
896
897 // helper function for LBM 2D -> swap Y and Z components everywhere
898 void ControlParticles::swapCoords(int a, int b) {
899         //return;
900         for(int i=0; i<(int)mPartSets.size(); i++) {
901                 for(int j=0; j<(int)mPartSets[i].particles.size(); j++) {
902                         TRISWAPALL( mPartSets[i].particles[j],a,b );
903                 }
904         }
905 }
906
907 // helper function for LBM 2D -> mirror time
908 void ControlParticles::mirrorTime() {
909         LbmFloat maxtime = mPartSets[mPartSets.size()-1].time;
910         const bool debugTimeswap = false;
911         
912         for(int i=0; i<(int)mPartSets.size(); i++) {
913                 mPartSets[i].time = maxtime - mPartSets[i].time;
914         }
915
916         for(int i=0; i<(int)mPartSets.size()/2; i++) {
917                 ControlParticleSet cps = mPartSets[i];
918                 if(debugTimeswap) errMsg("TIMESWAP", " s"<<i<<","<<mPartSets[i].time<<"  and s"<<(mPartSets.size()-1-i)<<","<< mPartSets[mPartSets.size()-1-i].time <<"  mt:"<<maxtime );
919                 mPartSets[i] = mPartSets[mPartSets.size()-1-i];
920                 mPartSets[mPartSets.size()-1-i] = cps;
921         }
922
923         for(int i=0; i<(int)mPartSets.size(); i++) {
924                 if(debugTimeswap) errMsg("TIMESWAP", "done: s"<<i<<","<<mPartSets[i].time<<"  "<<mPartSets[i].particles.size() );
925         }
926 }
927
928 // apply init transformations
929 void ControlParticles::applyTrafos() {
930         // apply trafos
931         for(int i=0; i<(int)mPartSets.size(); i++) {
932                 mPartSets[i].time *= _initTimeScale;
933                 /*for(int j=0; j<(int)mPartSets[i].particles.size(); j++) {
934                         for(int k=0; k<3; k++) {
935                                 mPartSets[i].particles[j].pos[k] *= _initPartScale[k];
936                                 mPartSets[i].particles[j].pos[k] += _initPartOffset[k];
937                         }
938                 } now done in initarray */
939         }
940
941         // mirror coords...
942         for(int l=0; l<(int)_initMirror.length(); l++) {
943                 switch(_initMirror[l]) {
944                 case 'X':
945                 case 'x':
946                         //printf("ControlParticles::applyTrafos - mirror x\n");
947                         swapCoords(1,2);
948                         break;
949                 case 'Y':
950                 case 'y':
951                         //printf("ControlParticles::applyTrafos - mirror y\n");
952                         swapCoords(0,2);
953                         break;
954                 case 'Z':
955                 case 'z':
956                         //printf("ControlParticles::applyTrafos - mirror z\n");
957                         swapCoords(0,1);
958                         break;
959                 case 'T':
960                 case 't':
961                         //printf("ControlParticles::applyTrafos - mirror time\n");
962                         mirrorTime();
963                         break;
964                 case ' ':
965                 case '-':
966                 case '\n':
967                         break;
968                 default:
969                         //printf("ControlParticles::applyTrafos - mirror unknown %c !?\n", _initMirror[l] );
970                         break;
971                 }
972         }
973
974         // reset 2d positions
975 #if (CP_PROJECT2D==1) && ( defined(MAIN_2D) || LBMDIM==2 )
976         for(size_t j=0; j<mPartSets.size(); j++) 
977                 for(size_t i=0; i<mPartSets[j].particles.size(); i++) {
978                         // DEBUG 
979                         mPartSets[j].particles[i].pos[1] = 0.f;
980                 }
981 #endif
982
983 #if defined(LBMDIM) 
984         //? if( (getenv("ELBEEM_CPINFILE")) || (getenv("ELBEEM_CPOUTFILE")) ){ 
985                 // gui control test, don swap...
986         //? } else {
987                 //? swapCoords(1,2); // LBM 2D -> swap Y and Z components everywhere
988         //? }
989 #endif
990
991         initTime(0.f, 0.f);
992 }
993
994 #undef TRISWAP
995
996 // --------------------------------------------------------------------------
997 // init for a given time
998 void ControlParticles::initTime(LbmFloat t, LbmFloat dt) 
999 {
1000         //fprintf(stdout, "CPINITTIME init %f\n",t);
1001         _currTime = t;
1002         if(mPartSets.size()<1) return;
1003
1004         // init zero velocities
1005         initTimeArray(t, _particles);
1006
1007         // calculate velocities from prev. timestep?
1008         if(dt>0.) {
1009                 _currTimestep = dt;
1010                 std::vector<ControlParticle> prevparts;
1011                 initTimeArray(t-dt, prevparts);
1012                 LbmFloat invdt = 1.0/dt;
1013                 for(size_t j=0; j<_particles.size(); j++) {
1014                         ControlParticle &p = _particles[j];
1015                         ControlParticle &prevp = prevparts[j];
1016                         for(int k=0; k<3; k++) {
1017                                 p.pos[k] *= _initPartScale[k];
1018                                 p.pos[k] += _initPartOffset[k];
1019                                 prevp.pos[k] *= _initLastPartScale[k];
1020                                 prevp.pos[k] += _initLastPartOffset[k];
1021                         }
1022                         p.vel = (p.pos - prevp.pos)*invdt;
1023                 }
1024
1025                 if(0) {
1026                         LbmVec avgvel(0.);
1027                         for(size_t j=0; j<_particles.size(); j++) {
1028                                 avgvel += _particles[j].vel;
1029                         }
1030                         avgvel /= (LbmFloat)_particles.size();
1031                         //fprintf(stdout," AVGVEL %f,%f,%f \n",avgvel[0],avgvel[1],avgvel[2]); // DEBUG
1032                 }
1033         }
1034 }
1035
1036 // helper, init given array
1037 void ControlParticles::initTimeArray(LbmFloat t, std::vector<ControlParticle> &parts) {
1038         if(mPartSets.size()<1) return;
1039
1040         if(parts.size()!=mPartSets[0].particles.size()) {
1041                 //fprintf(stdout,"PRES \n");
1042                 parts.resize(mPartSets[0].particles.size());
1043                 // TODO reset all?
1044                 for(size_t j=0; j<parts.size(); j++) {
1045                         parts[j].reset();
1046                 }
1047         }
1048         if(parts.size()<1) return;
1049
1050         // debug inits
1051         if(mDebugInit==1) {
1052                 // hard coded circle init
1053                 for(size_t j=0; j<mPartSets[0].particles.size(); j++) {
1054                         ControlParticle p = mPartSets[0].particles[j];
1055                         // remember old
1056                         p.density = parts[j].density;
1057                         p.densityWeight = parts[j].densityWeight;
1058                         p.avgVel = parts[j].avgVel;
1059                         p.avgVelAcc = parts[j].avgVelAcc;
1060                         p.avgVelWeight = parts[j].avgVelWeight;
1061                         LbmVec ppos(0.); { // DEBUG
1062                         const float tscale=10.;
1063                         const float tprevo = 0.33;
1064                         const LbmVec toff(50,50,0);
1065                         const LbmVec oscale(30,30,0);
1066                         ppos[0] =  cos(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[0] + toff[0];
1067                         ppos[1] = -sin(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[1] + toff[1];
1068                         ppos[2] =                               toff[2]; } // DEBUG
1069                         p.pos = ppos;
1070                         parts[j] = p;
1071                         //errMsg("ControlParticle::initTimeArray","j:"<<j<<" p:"<<parts[j].pos );
1072                 }
1073                 return;
1074         }
1075         else if(mDebugInit==2) {
1076                 // hard coded spiral init
1077                 const float tscale=-10.;
1078                 const float tprevo = 0.33;
1079                 LbmVec   toff(50,0,-50);
1080                 const LbmVec oscale(20,20,0);
1081                 toff[2] += 30. * t +30.;
1082                 for(size_t j=0; j<mPartSets[0].particles.size(); j++) {
1083                         ControlParticle p = mPartSets[0].particles[j];
1084                         // remember old
1085                         p.density = parts[j].density;
1086                         p.densityWeight = parts[j].densityWeight;
1087                         p.avgVel = parts[j].avgVel;
1088                         p.avgVelAcc = parts[j].avgVelAcc;
1089                         p.avgVelWeight = parts[j].avgVelWeight;
1090                         LbmVec ppos(0.); 
1091                         ppos[1] =                               toff[2]; 
1092                         LbmFloat zscal = (ppos[1]+100.)/200.;
1093                         ppos[0] =  cos(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[0]*zscal + toff[0];
1094                         ppos[2] = -sin(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[1]*zscal + toff[1];
1095                         p.pos = ppos;
1096                         parts[j] = p;
1097
1098                         toff[2] += 0.25;
1099                 }
1100                 return;
1101         }
1102
1103         // use first set
1104         if((t<=mPartSets[0].time)||(mPartSets.size()==1)) {
1105                 //fprintf(stdout,"PINI %f \n", t);
1106                 //parts = mPartSets[0].particles;
1107                 const int i=0;
1108                 for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
1109                         ControlParticle p = mPartSets[i].particles[j];
1110                         // remember old
1111                         p.density = parts[j].density;
1112                         p.densityWeight = parts[j].densityWeight;
1113                         p.avgVel = parts[j].avgVel;
1114                         p.avgVelAcc = parts[j].avgVelAcc;
1115                         p.avgVelWeight = parts[j].avgVelWeight;
1116                         parts[j] = p;
1117                 }
1118                 return;
1119         }
1120
1121         for(int i=0; i<(int)mPartSets.size()-1; i++) {
1122                 if((mPartSets[i].time<=t) && (mPartSets[i+1].time>t)) {
1123                         LbmFloat d = mPartSets[i+1].time-mPartSets[i].time;
1124                         LbmFloat f = (t-mPartSets[i].time)/d;
1125                         LbmFloat omf = 1.0f - f;
1126         
1127                         for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
1128                                 ControlParticle *src1=&mPartSets[i  ].particles[j];
1129                                 ControlParticle *src2=&mPartSets[i+1].particles[j];
1130                                 ControlParticle &p = parts[j];
1131                                 // do linear interpolation
1132                                 p.pos     = src1->pos * omf     + src2->pos *f;
1133                                 p.vel     = LbmVec(0.); // reset, calculated later on src1->vel * omf     + src2->vel *f;
1134                                 p.rotaxis = src1->rotaxis * omf + src2->rotaxis *f;
1135                                 p.influence = src1->influence * omf + src2->influence *f;
1136                                 p.size    = src1->size * omf    + src2->size *f;
1137                                 // dont modify: density, densityWeight
1138                         }
1139                 }
1140         }
1141
1142         // after last?
1143         if(t>=mPartSets[ mPartSets.size() -1 ].time) {
1144                 //parts = mPartSets[ mPartSets.size() -1 ].particles;
1145                 const int i= (int)mPartSets.size() -1;
1146                 for(size_t j=0; j<mPartSets[i].particles.size(); j++) {
1147                         ControlParticle p = mPartSets[i].particles[j];
1148                         // restore
1149                         p.density = parts[j].density;
1150                         p.densityWeight = parts[j].densityWeight;
1151                         p.avgVel = parts[j].avgVel;
1152                         p.avgVelAcc = parts[j].avgVelAcc;
1153                         p.avgVelWeight = parts[j].avgVelWeight;
1154                         parts[j] = p;
1155                 }
1156         }
1157 }
1158
1159
1160
1161
1162 // --------------------------------------------------------------------------
1163
1164 #define DEBUG_MODVEL 0
1165
1166 // recalculate 
1167 void ControlParticles::calculateKernelWeight() {
1168         const bool debugKernel = true;
1169
1170         // calculate kernel area with respect to particlesize/cellsize
1171         LbmFloat kernelw = -1.;
1172         LbmFloat kernelnorm = -1.;
1173         LbmFloat krad = (_radiusAtt*0.75); // FIXME  use real cone approximation...?
1174         //krad = (_influenceFalloff*1.);
1175 #if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
1176         kernelw = CP_PI*krad*krad;
1177         kernelnorm = 1.0 / (_fluidSpacing * _fluidSpacing);
1178 #else // 2D
1179         kernelw = CP_PI*krad*krad*krad* (4./3.);
1180         kernelnorm = 1.0 / (_fluidSpacing * _fluidSpacing * _fluidSpacing);
1181 #endif // MAIN_2D
1182
1183         if(debugKernel) debMsgStd("ControlParticles::calculateKernelWeight",DM_MSG,"kw"<<kernelw<<", norm"<<
1184                         kernelnorm<<", w*n="<<(kernelw*kernelnorm)<<", rad"<<krad<<", sp"<<_fluidSpacing<<"  ", 7);
1185         LbmFloat kernelws = kernelw*kernelnorm;
1186         _kernelWeight = kernelws;
1187         if(debugKernel) debMsgStd("ControlParticles::calculateKernelWeight",DM_MSG,"influence f="<<_radiusAtt<<" t="<<
1188                         _influenceTangential<<" a="<<_influenceAttraction<<" v="<<_influenceVelocity<<" kweight="<<_kernelWeight, 7);
1189         if(_kernelWeight<=0.) {
1190                 errMsg("ControlParticles::calculateKernelWeight", "invalid kernel! "<<_kernelWeight<<", resetting");
1191                 _kernelWeight = 1.;
1192         }
1193 }
1194
1195 void 
1196 ControlParticles::prepareControl(LbmFloat simtime, LbmFloat dt, ControlParticles *motion) {
1197         debMsgStd("ControlParticle::prepareControl",DM_MSG," simtime="<<simtime<<" dt="<<dt<<" ", 5);
1198
1199         //fprintf(stdout,"PREPARE \n");
1200         LbmFloat avgdw = 0.;
1201         for(size_t i=0; i<_particles.size(); i++) {
1202                 ControlParticle *cp = &_particles[i];
1203
1204                 if(this->getInfluenceAttraction()<0.) {
1205                         cp->density= 
1206                         cp->densityWeight = 1.0;
1207                         continue;
1208                 } 
1209
1210                 // normalize by kernel 
1211                 //cp->densityWeight = (1.0 - (cp->density / _kernelWeight)); // store last
1212 #if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
1213                 cp->densityWeight = (1.0 - (cp->density / (_kernelWeight*cp->size*cp->size) )); // store last
1214 #else // 2D
1215                 cp->densityWeight = (1.0 - (cp->density / (_kernelWeight*cp->size*cp->size*cp->size) )); // store last
1216 #endif // MAIN_2D
1217
1218                 if(i<10) debMsgStd("ControlParticle::prepareControl",DM_MSG,"kernelDebug i="<<i<<" densWei="<<cp->densityWeight<<" 1/kw"<<(1.0/_kernelWeight)<<" cpdensity="<<cp->density, 9 );
1219                 if(cp->densityWeight<0.) cp->densityWeight=0.;
1220                 if(cp->densityWeight>1.) cp->densityWeight=1.;
1221                 
1222                 avgdw += cp->densityWeight;
1223                 // reset for next step
1224                 cp->density = 0.; 
1225
1226                 if(cp->avgVelWeight>0.) {
1227                  cp->avgVel     = cp->avgVelAcc/cp->avgVelWeight; 
1228                  cp->avgVelWeight       = 0.; 
1229                  cp->avgVelAcc  = LbmVec(0.,0.,0.); 
1230                 }
1231         }
1232         //if(debugKernel) for(size_t i=0; i<_particles.size(); i++) { ControlParticle *cp = &_particles[i]; fprintf(stdout,"A %f,%f \n",cp->density,cp->densityWeight); }
1233         avgdw /= (LbmFloat)(_particles.size());
1234         //if(motion) { printf("ControlParticle::kernel: avgdw:%f,  kw%f, sp%f \n", avgdw, _kernelWeight, _fluidSpacing); }
1235         
1236         //if((simtime>=0.) && (simtime != _currTime)) 
1237         initTime(simtime, dt);
1238
1239         if((motion) && (motion->getSize()>0)){
1240                 ControlParticle *motionp = motion->getParticle(0);
1241                 //printf("ControlParticle::prepareControl motion: pos[%f,%f,%f] vel[%f,%f,%f] \n", motionp->pos[0], motionp->pos[1], motionp->pos[2], motionp->vel[0], motionp->vel[1], motionp->vel[2] );
1242                 for(size_t i=0; i<_particles.size(); i++) {
1243                         ControlParticle *cp = &_particles[i];
1244                         cp->pos = cp->pos + motionp->pos;
1245                         cp->vel = cp->vel + motionp->vel;
1246                         cp->size = cp->size * motionp->size;
1247                         cp->influence = cp->size * motionp->influence;
1248                 }
1249         }
1250         
1251         // reset to radiusAtt by default
1252         if(_radiusVel==0.) _radiusVel = _radiusAtt;
1253         if(_radiusMinMaxd==0.) _radiusMinMaxd = _radiusAtt;
1254         if(_radiusMaxd==0.) _radiusMaxd = 2.*_radiusAtt;
1255         // has to be radiusVel<radiusAtt<radiusMinMaxd<radiusMaxd
1256         if(_radiusVel>_radiusAtt) _radiusVel = _radiusAtt;
1257         if(_radiusAtt>_radiusMinMaxd) _radiusAtt = _radiusMinMaxd;
1258         if(_radiusMinMaxd>_radiusMaxd) _radiusMinMaxd = _radiusMaxd;
1259
1260         //printf("ControlParticle::radii vel:%f att:%f min:%f max:%f \n", _radiusVel,_radiusAtt,_radiusMinMaxd,_radiusMaxd);
1261         // prepareControl done
1262 }
1263
1264 void ControlParticles::finishControl(std::vector<ControlForces> &forces, LbmFloat iatt, LbmFloat ivel, LbmFloat imaxd) {
1265
1266         //const LbmFloat iatt  = this->getInfluenceAttraction() * this->getCurrTimestep();
1267         //const LbmFloat ivel  = this->getInfluenceVelocity();
1268         //const LbmFloat imaxd = this->getInfluenceMaxdist() * this->getCurrTimestep();
1269         // prepare for usage
1270         iatt  *= this->getCurrTimestep();
1271         ivel  *= 1.; // not necessary!
1272         imaxd *= this->getCurrTimestep();
1273
1274         // skip when size=0
1275         for(int i=0; i<(int)forces.size(); i++) {
1276                 if(DEBUG_MODVEL) fprintf(stdout, "CPFORGF %d , wf:%f,f:%f,%f,%f  ,  v:%f,%f,%f   \n",i, forces[i].weightAtt, forces[i].forceAtt[0],forces[i].forceAtt[1],forces[i].forceAtt[2],   forces[i].forceVel[0], forces[i].forceVel[1], forces[i].forceVel[2] );
1277                 LbmFloat cfweight = forces[i].weightAtt; // always normalize
1278                 if((cfweight!=0.)&&(iatt!=0.)) {
1279                         // multiple kernels, normalize - note this does not normalize in d>r/2 region
1280                         if(ABS(cfweight)>1.) { cfweight = 1.0/cfweight; }
1281                         // multiply iatt afterwards to allow stronger force
1282                         cfweight *= iatt;
1283                         forces[i].forceAtt *= cfweight;
1284                 } else {
1285                         forces[i].weightAtt =  0.;
1286                         forces[i].forceAtt = LbmVec(0.);
1287                 }
1288
1289                 if( (cfweight==0.) && (imaxd>0.) && (forces[i].maxDistance>0.) ) {
1290                         forces[i].forceMaxd *= imaxd;
1291                 } else {
1292                         forces[i].maxDistance=  0.;
1293                         forces[i].forceMaxd = LbmVec(0.);
1294                 }
1295
1296                 LbmFloat cvweight = forces[i].weightVel; // always normalize
1297                 if(cvweight>0.) {
1298                         forces[i].forceVel /= cvweight;
1299                         forces[i].compAv /= cvweight;
1300                         // now modify cvweight, and write back
1301                         // important, cut at 1 - otherwise strong vel. influences...
1302                         if(cvweight>1.) { cvweight = 1.; }
1303                         // thus cvweight is in the range of 0..influenceVelocity, currently not normalized by numCParts
1304                         cvweight *= ivel;
1305                         if(cvweight<0.) cvweight=0.; if(cvweight>1.) cvweight=1.;
1306                         // LBM, FIXME todo use relaxation factor
1307                         //pvel = (cvel*0.5 * cvweight) + (pvel * (1.0-cvweight)); 
1308                         forces[i].weightVel = cvweight;
1309
1310                         //errMsg("COMPAV","i"<<i<<" compav"<<forces[i].compAv<<" forcevel"<<forces[i].forceVel<<" ");
1311                 } else {
1312                         forces[i].weightVel = 0.;
1313                         if(forces[i].maxDistance==0.) forces[i].forceVel = LbmVec(0.);
1314                         forces[i].compAvWeight = 0.;
1315                         forces[i].compAv = LbmVec(0.);
1316                 }
1317                 if(DEBUG_MODVEL) fprintf(stdout, "CPFINIF %d , wf:%f,f:%f,%f,%f  ,  v:%f,%f,%f   \n",i, forces[i].weightAtt, forces[i].forceAtt[0],forces[i].forceAtt[1],forces[i].forceAtt[2],  forces[i].forceVel[0],forces[i].forceVel[1],forces[i].forceVel[2] );
1318         }
1319
1320         // unused...
1321         if(DEBUG_MODVEL) fprintf(stdout,"MFC iatt:%f,%f ivel:%f,%f ifmd:%f,%f \n", iatt,_radiusAtt, ivel,_radiusVel, imaxd, _radiusMaxd);
1322         //for(size_t i=0; i<_particles.size(); i++) { ControlParticle *cp = &_particles[i]; fprintf(stdout," %f,%f,%f ",cp->density,cp->densityWeight, (1.0 - (12.0*cp->densityWeight))); }
1323         //fprintf(stdout,"\n\nCP DONE \n\n\n");
1324 }
1325
1326
1327 // --------------------------------------------------------------------------
1328 // calculate forces at given position, and modify velocity
1329 // according to timestep
1330 void ControlParticles::calculateCpInfluenceOpt(ControlParticle *cp, LbmVec fluidpos, LbmVec fluidvel, ControlForces *force, LbmFloat fillFactor) {
1331         // dont reset, only add...
1332         // test distance, simple squared distance reject
1333         const LbmFloat cpfo = _radiusAtt*cp->size;
1334
1335         LbmVec posDelta;
1336         if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f bef fw:%f, f:%f,%f,%f  , vw:%f, v:%f,%f,%f   \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
1337         posDelta        = cp->pos - fluidpos;
1338 #if LBMDIM==2 && (CP_PROJECT2D==1)
1339         posDelta[2] = 0.; // project to xy plane, z-velocity should already be gone...
1340 #endif
1341
1342         const LbmFloat distsqr = posDelta[0]*posDelta[0]+posDelta[1]*posDelta[1]+posDelta[2]*posDelta[2];
1343         if(DEBUG_MODVEL) fprintf(stdout, " Pd at %f,%f,%f d%f   \n",posDelta[0],posDelta[1],posDelta[2], distsqr);
1344         // cut at influence=0.5 , scaling not really makes sense
1345         if(cpfo*cpfo < distsqr) {
1346                 /*if(cp->influence>0.5) {
1347                         if(force->weightAtt == 0.) {
1348                                 if(force->maxDistance*force->maxDistance > distsqr) {
1349                                 const LbmFloat dis = sqrtf((float)distsqr);
1350                                 const LbmFloat sc = dis-cpfo;
1351                                 force->maxDistance = dis;
1352                                 force->forceMaxd = (posDelta)*(sc/dis);
1353                                 }
1354                         } } */
1355                 return;
1356         }
1357         force->weightAtt += 1e-6; // for distance
1358         force->maxDistance = 0.; // necessary for SPH?
1359
1360         const LbmFloat pdistance = MAGNITUDE(posDelta);
1361         LbmFloat pdistinv = 0.;
1362         if(ABS(pdistance)>0.) pdistinv = 1./pdistance;
1363         posDelta *= pdistinv;
1364
1365         LbmFloat falloffAtt = 0.; //CPKernel::kernel(cpfo * 1.0, pdistance);
1366         const LbmFloat qac = pdistance / cpfo ;
1367         if (qac < 1.0){ // return 0.;
1368                 if(qac < 0.5) falloffAtt =  1.0f;
1369                 else         falloffAtt = (1.0f - qac) * 2.0f;
1370         }
1371
1372         // vorticity force:
1373         // - //LbmVec forceVort; 
1374         // - //CROSS(forceVort, posDelta, cp->rotaxis);
1375         // - //NORMALIZE(forceVort);
1376         // - if(falloffAtt>1.0) falloffAtt=1.0;
1377
1378 #if (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
1379         // fillFactor *= 2.0 *0.75 * pdistance; // 2d>3d sampling
1380 #endif // (CP_PROJECT2D==1) && (defined(MAIN_2D) || LBMDIM==2)
1381         cp->density += falloffAtt * fillFactor;
1382         force->forceAtt += posDelta *cp->densityWeight *cp->influence; 
1383         force->weightAtt += falloffAtt*cp->densityWeight *cp->influence;
1384         
1385         LbmFloat falloffVel = 0.; //CPKernel::kernel(cpfo * 1.0, pdistance);
1386         const LbmFloat cpfv = _radiusVel*cp->size;
1387         if(cpfv*cpfv < distsqr) { return; }
1388         const LbmFloat qvc = pdistance / cpfo ;
1389         //if (qvc < 1.0){ 
1390                 //if(qvc < 0.5) falloffVel =  1.0f;
1391                 //else         falloffVel = (1.0f - qvc) * 2.0f;
1392         //}
1393         falloffVel = 1.-qvc;
1394
1395         LbmFloat pvWeight; // = (1.0-cp->densityWeight) * _currTimestep * falloffVel;
1396         pvWeight = falloffVel *cp->influence; // std, without density influence
1397         //pvWeight *= (1.0-cp->densityWeight); // use inverse density weight
1398         //pvWeight *=      cp->densityWeight; // test, use density weight
1399         LbmVec modvel(0.);
1400         modvel += cp->vel * pvWeight;
1401         //pvWeight = 1.; modvel = partVel; // DEBUG!?
1402
1403         if(pvWeight>0.) {
1404                 force->forceVel += modvel;
1405                 force->weightVel += pvWeight;
1406
1407                 cp->avgVelWeight += falloffVel;
1408                 cp->avgVel += fluidvel;
1409         } 
1410         if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f aft fw:%f, f:%f,%f,%f  , vw:%f, v:%f,%f,%f   \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
1411         return;
1412 }
1413
1414 void ControlParticles::calculateMaxdForce(ControlParticle *cp, LbmVec fluidpos, ControlForces *force) {
1415         if(force->weightAtt != 0.) return; // maxd force off
1416         if(cp->influence <= 0.5) return;   // ignore
1417
1418         LbmVec posDelta;
1419         //if(DEBUG_MODVEL) fprintf(stdout, "CP at %f,%f,%f bef fw:%f, f:%f,%f,%f  , vw:%f, v:%f,%f,%f   \n",fluidpos[0],fluidpos[1],fluidpos[2], force->weightAtt, force->forceAtt[0], force->forceAtt[1], force->forceAtt[2], force->weightVel, force->forceVel[0], force->forceVel[1], force->forceVel[2]);
1420         posDelta        = cp->pos - fluidpos;
1421 #if LBMDIM==2 && (CP_PROJECT2D==1)
1422         posDelta[2] = 0.; // project to xy plane, z-velocity should already be gone...
1423 #endif
1424
1425         // dont reset, only add...
1426         // test distance, simple squared distance reject
1427         const LbmFloat distsqr = posDelta[0]*posDelta[0]+posDelta[1]*posDelta[1]+posDelta[2]*posDelta[2];
1428         
1429         // closer cp found
1430         if(force->maxDistance*force->maxDistance < distsqr) return;
1431         
1432         const LbmFloat dmin = _radiusMinMaxd*cp->size;
1433         if(distsqr<dmin*dmin) return; // inside min
1434         const LbmFloat dmax = _radiusMaxd*cp->size;
1435         if(distsqr>dmax*dmax) return; // outside
1436
1437
1438         if(DEBUG_MODVEL) fprintf(stdout, " Pd at %f,%f,%f d%f   \n",posDelta[0],posDelta[1],posDelta[2], distsqr);
1439         // cut at influence=0.5 , scaling not really makes sense
1440         const LbmFloat dis = sqrtf((float)distsqr);
1441         //const LbmFloat sc = dis - dmin;
1442         const LbmFloat sc = (dis-dmin)/(dmax-dmin); // scale from 0-1
1443         force->maxDistance = dis;
1444         force->forceMaxd = (posDelta/dis) * sc;
1445         //debug errMsg("calculateMaxdForce","pos"<<fluidpos<<" dis"<<dis<<" sc"<<sc<<" dmin"<<dmin<<" maxd"<< force->maxDistance <<" fmd"<<force->forceMaxd );
1446         return;
1447 }
1448