elbeem update:
[blender.git] / intern / elbeem / intern / ntl_geometryobject.cpp
1 /******************************************************************************
2  *
3  * El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
4  * Copyright 2003,2004 Nils Thuerey
5  *
6  * a geometry object
7  * all other geometry objects are derived from this one
8  *
9  *****************************************************************************/
10
11
12 #include "ntl_geometryobject.h"
13 #include "ntl_world.h"
14 #include "ntl_matrices.h"
15
16 // for FGI
17 #include "elbeem.h"
18
19
20
21 /*****************************************************************************/
22 /* Default constructor */
23 /*****************************************************************************/
24 ntlGeometryObject::ntlGeometryObject() :
25         mIsInitialized(false), mpMaterial( NULL ),
26         mMaterialName( "default" ),
27         mCastShadows( 1 ), mReceiveShadows( 1 ),
28         mGeoInitType( 0 ), 
29         mInitialVelocity(0.0), mcInitialVelocity(0.0), mLocalCoordInivel(false),
30         mGeoInitIntersect(false),
31         mGeoPartSlipValue(0.0),
32         mVolumeInit(VOLUMEINIT_VOLUME),
33         mInitialPos(0.),
34         mcTrans(0.), mcRot(0.), mcScale(1.),
35         mIsAnimated(false),
36         mMovPoints(), mMovNormals(),
37         mHaveCachedMov(false),
38         mCachedMovPoints(), mCachedMovNormals(),
39         mTriangleDivs1(), mTriangleDivs2(), mTriangleDivs3(),
40         mMovPntsInited(-100.0), mMaxMovPnt(-1),
41         mcGeoActive(1.)
42
43 };
44
45
46 /*****************************************************************************/
47 /* Default destructor */
48 /*****************************************************************************/
49 ntlGeometryObject::~ntlGeometryObject() 
50 {
51 }
52
53 /*! is the mesh animated? */
54 bool ntlGeometryObject::getMeshAnimated() {
55         // off by default, on for e.g. ntlGeometryObjModel
56         return false; 
57 }
58
59 /*! init object anim flag */
60 bool ntlGeometryObject::checkIsAnimated() {
61         if(    (mcTrans.accessValues().size()>1)  // VALIDATE
62             || (mcRot.accessValues().size()>1) 
63             || (mcScale.accessValues().size()>1) 
64             || (mcGeoActive.accessValues().size()>1) 
65             || (mcInitialVelocity.accessValues().size()>1) 
66                 ) {
67                 mIsAnimated = true;
68         }
69
70         // fluid objects always have static init!
71         if(mGeoInitType==FGI_FLUID) {
72                 mIsAnimated=false;
73         }
74         return mIsAnimated;
75 }
76
77 /*****************************************************************************/
78 /* Init attributes etc. of this object */
79 /*****************************************************************************/
80 #define GEOINIT_STRINGS  9
81 static char *initStringStrs[GEOINIT_STRINGS] = {
82         "fluid",
83         "bnd_no","bnd_noslip",
84         "bnd_free","bnd_freeslip",
85         "bnd_part","bnd_partslip",
86         "inflow", "outflow"
87 };
88 static int initStringTypes[GEOINIT_STRINGS] = {
89         FGI_FLUID,
90         FGI_BNDNO, FGI_BNDNO,
91         FGI_BNDFREE, FGI_BNDFREE,
92         FGI_BNDPART, FGI_BNDPART,
93         FGI_MBNDINFLOW, FGI_MBNDOUTFLOW
94 };
95 void ntlGeometryObject::initialize(ntlRenderGlobals *glob) 
96 {
97         //debugOut("ntlGeometryObject::initialize: '"<<getName()<<"' ", 10);
98         // initialize only once...
99         if(mIsInitialized) return;
100         
101         // init material, always necessary
102         searchMaterial( glob->getMaterials() );
103         
104         this->mGeoInitId = mpAttrs->readInt("geoinitid", this->mGeoInitId,"ntlGeometryObject", "mGeoInitId", false);
105         mGeoInitIntersect = mpAttrs->readInt("geoinit_intersect", mGeoInitIntersect,"ntlGeometryObject", "mGeoInitIntersect", false);
106         string ginitStr = mpAttrs->readString("geoinittype", "", "ntlGeometryObject", "mGeoInitType", false);
107         if(this->mGeoInitId>=0) {
108                 bool gotit = false;
109                 for(int i=0; i<GEOINIT_STRINGS; i++) {
110                         if(ginitStr== initStringStrs[i]) {
111                                 gotit = true;
112                                 mGeoInitType = initStringTypes[i];
113                         }
114                 }
115
116                 if(!gotit) {
117                         errFatal("ntlGeometryObject::initialize","Obj '"<<mName<<"', Unkown 'geoinittype' value: '"<< ginitStr <<"' ", SIMWORLD_INITERROR);
118                         return;
119                 }
120         }
121
122         int geoActive = mpAttrs->readInt("geoinitactive", 1,"ntlGeometryObject", "geoActive", false);
123         if(!geoActive) {
124                 // disable geo init again...
125                 this->mGeoInitId = -1;
126         }
127         mInitialVelocity  = vec2G( mpAttrs->readVec3d("initial_velocity", vec2D(mInitialVelocity),"ntlGeometryObject", "mInitialVelocity", false));
128         if(getAttributeList()->exists("initial_velocity") || (!mcInitialVelocity.isInited()) ) {
129                 mcInitialVelocity = mpAttrs->readChannelVec3f("initial_velocity");
130         }
131         // always use channel
132         if(!mcInitialVelocity.isInited()) { mcInitialVelocity = AnimChannel<ntlVec3Gfx>(mInitialVelocity); }
133         mLocalCoordInivel = mpAttrs->readBool("geoinit_localinivel", mLocalCoordInivel,"ntlGeometryObject", "mLocalCoordInivel", false);
134
135         mGeoPartSlipValue = mpAttrs->readFloat("geoinit_partslip", mGeoPartSlipValue,"ntlGeometryObject", "mGeoPartSlipValue", false);
136         bool mOnlyThinInit = false; // deprecated!
137         mOnlyThinInit     = mpAttrs->readBool("geoinit_onlythin", mOnlyThinInit,"ntlGeometryObject", "mOnlyThinInit", false);
138         if(mOnlyThinInit) mVolumeInit = VOLUMEINIT_SHELL;
139         mVolumeInit     = mpAttrs->readInt("geoinit_volumeinit", mVolumeInit,"ntlGeometryObject", "mVolumeInit", false);
140         if((mVolumeInit<VOLUMEINIT_VOLUME)||(mVolumeInit>VOLUMEINIT_BOTH)) mVolumeInit = VOLUMEINIT_VOLUME;
141
142         // override cfg types
143         mVisible = mpAttrs->readBool("visible", mVisible,"ntlGeometryObject", "mVisible", false);
144         mReceiveShadows = mpAttrs->readBool("recv_shad", mReceiveShadows,"ntlGeometryObject", "mReceiveShadows", false);
145         mCastShadows = mpAttrs->readBool("cast_shad", mCastShadows,"ntlGeometryObject", "mCastShadows", false);
146
147         // read mesh animation channels
148         ntlVec3d translation(0.0);
149         translation = mpAttrs->readVec3d("translation", translation,"ntlGeometryObject", "translation", false);
150         if(getAttributeList()->exists("translation") || (!mcTrans.isInited()) ) {
151                 mcTrans = mpAttrs->readChannelVec3f("translation");
152         }
153         ntlVec3d rotation(0.0);
154         rotation = mpAttrs->readVec3d("rotation", rotation,"ntlGeometryObject", "rotation", false);
155         if(getAttributeList()->exists("rotation") || (!mcRot.isInited()) ) {
156                 mcRot = mpAttrs->readChannelVec3f("rotation");
157         }
158         ntlVec3d scale(1.0);
159         scale = mpAttrs->readVec3d("scale", scale,"ntlGeometryObject", "scale", false);
160         if(getAttributeList()->exists("scale") || (!mcScale.isInited()) ) {
161                 mcScale = mpAttrs->readChannelVec3f("scale");
162         }
163
164         float geoactive=1.;
165         geoactive = mpAttrs->readFloat("geoactive", geoactive,"ntlGeometryObject", "geoactive", false);
166         if(getAttributeList()->exists("geoactive") || (!mcGeoActive.isInited()) ) {
167                 mcGeoActive = mpAttrs->readChannelFloat("geoactive");
168         }
169         // always use channel
170         if(!mcGeoActive.isInited()) { mcGeoActive = AnimChannel<double>(geoactive); }
171
172         checkIsAnimated();
173
174         mIsInitialized = true;
175         debMsgStd("ntlGeometryObject::initialize",DM_MSG,"GeoObj '"<<this->getName()<<"': visible="<<this->mVisible<<" gid="<<this->mGeoInitId<<" gtype="<<mGeoInitType<<","<<ginitStr<<
176                         " gvel="<<mInitialVelocity<<" gisect="<<mGeoInitIntersect, 10); // debug
177 }
178
179 /*! notify object that dump is in progress (e.g. for particles) */
180 // default action - do nothing...
181 void ntlGeometryObject::notifyOfDump(int dumtp, int frameNr,char *frameNrStr,string outfilename, double simtime) {
182   bool debugOut=false;
183         if(debugOut) debMsgStd("ntlGeometryObject::notifyOfDump",DM_MSG," dt:"<<dumtp<<" obj:"<<this->getName()<<" frame:"<<frameNrStr<<","<<frameNr<<",t"<<simtime<<" to "<<outfilename, 10); // DEBUG
184 }
185
186 /*****************************************************************************/
187 /* Search the material for this object from the material list */
188 /*****************************************************************************/
189 void ntlGeometryObject::searchMaterial(vector<ntlMaterial *> *mat)
190 {
191         /* search the list... */
192         int i=0;
193         for (vector<ntlMaterial*>::iterator iter = mat->begin();
194          iter != mat->end(); iter++) {
195                 if( mMaterialName == (*iter)->getName() ) {
196                         //warnMsg("ntlGeometryObject::searchMaterial","for obj '"<<getName()<<"' found - '"<<(*iter)->getName()<<"' "<<i); // DEBUG
197                         mpMaterial = (*iter);
198                         return;
199                 }
200                 i++;
201         }
202         errFatal("ntlGeometryObject::searchMaterial","Unknown material '"<<mMaterialName<<"' ! ", SIMWORLD_INITERROR);
203         mpMaterial = new ntlMaterial();
204         return;
205 }
206
207 /******************************************************************************
208  * static add triangle function
209  *****************************************************************************/
210 void ntlGeometryObject::sceneAddTriangle(
211                 ntlVec3Gfx  p1,ntlVec3Gfx  p2,ntlVec3Gfx  p3,
212                 ntlVec3Gfx pn1,ntlVec3Gfx pn2,ntlVec3Gfx pn3,
213                 ntlVec3Gfx trin, bool smooth,
214                 vector<ntlTriangle> *triangles,
215                 vector<ntlVec3Gfx>  *vertices,
216                 vector<ntlVec3Gfx>  *normals) {
217         ntlTriangle tri;
218         int tempVert;
219   
220         if(normals->size() != vertices->size()) {
221                 errFatal("ntlGeometryObject::sceneAddTriangle","For '"<<this->mName<<"': Vertices and normals sizes to not match!!!",SIMWORLD_GENERICERROR);
222
223         } else {
224                 
225                 vertices->push_back( p1 ); 
226                 normals->push_back( pn1 ); 
227                 tempVert = normals->size()-1;
228                 tri.getPoints()[0] = tempVert;
229                 
230                 vertices->push_back( p2 ); 
231                 normals->push_back( pn2 ); 
232                 tempVert = normals->size()-1;
233                 tri.getPoints()[1] = tempVert;
234                 
235                 vertices->push_back( p3 ); 
236                 normals->push_back( pn3 ); 
237                 tempVert = normals->size()-1;
238                 tri.getPoints()[2] = tempVert;
239                 
240                 
241                 /* init flags from ntl_ray.h */
242                 int flag = 0; 
243                 if(getVisible()){ flag |= TRI_GEOMETRY; }
244                 if(getCastShadows() ) { 
245                         flag |= TRI_CASTSHADOWS; } 
246                 
247                 /* init geo init id */
248                 int geoiId = getGeoInitId(); 
249                 //if((geoiId > 0) && (mVolumeInit&VOLUMEINIT_VOLUME) && (!mIsAnimated)) { 
250                 if((geoiId > 0) && (mVolumeInit&VOLUMEINIT_VOLUME)) { 
251                         flag |= (1<< (geoiId+4)); 
252                         flag |= mGeoInitType; 
253                 } 
254                 /*errMsg("ntlScene::addTriangle","DEBUG flag="<<convertFlags2String(flag) ); */ 
255                 tri.setFlags( flag );
256                 
257                 /* triangle normal missing */
258                 tri.setNormal( trin );
259                 tri.setSmoothNormals( smooth );
260                 tri.setObjectId( this->mObjectId );
261                 triangles->push_back( tri ); 
262         } /* normals check*/ 
263 }
264
265 void ntlGeometryObject::sceneAddTriangleNoVert(int *trips,
266                 ntlVec3Gfx trin, bool smooth,
267                 vector<ntlTriangle> *triangles) {
268         ntlTriangle tri;
269                 
270         tri.getPoints()[0] = trips[0];
271         tri.getPoints()[1] = trips[1];
272         tri.getPoints()[2] = trips[2];
273
274         // same as normal sceneAddTriangle
275
276         /* init flags from ntl_ray.h */
277         int flag = 0; 
278         if(getVisible()){ flag |= TRI_GEOMETRY; }
279         if(getCastShadows() ) { 
280                 flag |= TRI_CASTSHADOWS; } 
281
282         /* init geo init id */
283         int geoiId = getGeoInitId(); 
284         if((geoiId > 0) && (mVolumeInit&VOLUMEINIT_VOLUME)) { 
285                 flag |= (1<< (geoiId+4)); 
286                 flag |= mGeoInitType; 
287         } 
288         /*errMsg("ntlScene::addTriangle","DEBUG flag="<<convertFlags2String(flag) ); */ 
289         tri.setFlags( flag );
290
291         /* triangle normal missing */
292         tri.setNormal( trin );
293         tri.setSmoothNormals( smooth );
294         tri.setObjectId( this->mObjectId );
295         triangles->push_back( tri ); 
296 }
297
298
299 /******************************************************************************/
300 /* Init channels from float arrays (for elbeem API) */
301 /******************************************************************************/
302
303 #define ADD_CHANNEL_VEC(dst,nvals,val) \
304                 vals.clear(); time.clear(); elbeemSimplifyChannelVec3(val,&nvals); \
305                 for(int i=0; i<(nvals); i++) { \
306                         vals.push_back(ntlVec3Gfx((val)[i*4+0], (val)[i*4+1],(val)[i*4+2] )); \
307                         time.push_back( (val)[i*4+3] ); \
308                 } \
309                 (dst) = AnimChannel< ntlVec3Gfx >(vals,time); 
310
311 #define ADD_CHANNEL_FLOAT(dst,nvals,val) \
312                 valsd.clear(); time.clear(); elbeemSimplifyChannelFloat(val,&nvals); \
313                 for(int i=0; i<(nvals); i++) { \
314                         valsd.push_back( (val)[i*2+0] ); \
315                         time.push_back( (val)[i*2+1] ); \
316                 } \
317                 (dst) = AnimChannel< double >(valsd,time); 
318
319 void ntlGeometryObject::initChannels(
320                 int nTrans, float *trans, int nRot, float *rot, int nScale, float *scale,
321                 int nAct, float *act, int nIvel, float *ivel
322                 ) {
323         const bool debugInitc=true;
324         if(debugInitc) { debMsgStd("ntlGeometryObject::initChannels",DM_MSG,"nt:"<<nTrans<<" nr:"<<nRot<<" ns:"<<nScale, 10); 
325                          debMsgStd("ntlGeometryObject::initChannels",DM_MSG,"na:"<<nAct<<" niv:"<<nIvel<<" ", 10); }
326         vector<ntlVec3Gfx> vals;
327         vector<double> valsd;
328         vector<double> time;
329         if((trans)&&(nTrans>0)) {  ADD_CHANNEL_VEC(mcTrans, nTrans, trans); }
330         if((rot)&&(nRot>0)) {      ADD_CHANNEL_VEC(mcRot, nRot, rot); }
331         if((scale)&&(nScale>0)) {  ADD_CHANNEL_VEC(mcScale, nScale, scale); }
332         if((act)&&(nAct>0)) {      ADD_CHANNEL_FLOAT(mcGeoActive, nAct, act); }
333         if((ivel)&&(nIvel>0)) {    ADD_CHANNEL_VEC(mcInitialVelocity, nIvel, ivel); }
334
335         checkIsAnimated();
336         if(debugInitc) { 
337                 debMsgStd("ntlGeometryObject::initChannels",DM_MSG,getName()<<
338                                 " nt:"<<mcTrans.accessValues().size()<<" nr:"<<mcRot.accessValues().size()<<
339                                 " ns:"<<mcScale.accessValues().size()<<" isAnim:"<<mIsAnimated, 10); }
340
341         if(debugInitc) {
342                 std::ostringstream ostr;
343                 ostr << "trans: ";
344                 for(size_t i=0; i<mcTrans.accessValues().size(); i++) {
345                         ostr<<" "<<mcTrans.accessValues()[i]<<"@"<<mcTrans.accessTimes()[i]<<" ";
346                 } ostr<<";   ";
347                 ostr<<"rot: ";
348                 for(size_t i=0; i<mcRot.accessValues().size(); i++) {
349                         ostr<<" "<<mcRot.accessValues()[i]<<"@"<<mcRot.accessTimes()[i]<<" ";
350                 } ostr<<";   ";
351                 ostr<<"scale: ";
352                 for(size_t i=0; i<mcScale.accessValues().size(); i++) {
353                         ostr<<" "<<mcScale.accessValues()[i]<<"@"<<mcScale.accessTimes()[i]<<" ";
354                 } ostr<<";   ";
355                 ostr<<"act: ";
356                 for(size_t i=0; i<mcGeoActive.accessValues().size(); i++) {
357                         ostr<<" "<<mcGeoActive.accessValues()[i]<<"@"<<mcGeoActive.accessTimes()[i]<<" ";
358                 } ostr<<";   ";
359                 ostr<<"ivel: ";
360                 for(size_t i=0; i<mcInitialVelocity.accessValues().size(); i++) {
361                         ostr<<" "<<mcInitialVelocity.accessValues()[i]<<"@"<<mcInitialVelocity.accessTimes()[i]<<" ";
362                 } ostr<<";   ";
363                 debMsgStd("ntlGeometryObject::initChannels",DM_MSG,"Inited "<<ostr.str(),10);
364         }
365 }
366 #undef ADD_CHANNEL
367
368
369 /*****************************************************************************/
370 /* apply object translation at time t*/
371 /*****************************************************************************/
372 void ntlGeometryObject::applyTransformation(double t, vector<ntlVec3Gfx> *verts, vector<ntlVec3Gfx> *norms, int vstart, int vend, int forceTrafo) {
373         if(    (mcTrans.accessValues().size()>1)  // VALIDATE
374             || (mcRot.accessValues().size()>1) 
375             || (mcScale.accessValues().size()>1) 
376             || (forceTrafo)
377             || (!mHaveCachedMov)
378                 ) {
379                 // transformation is animated, continue
380                 ntlVec3Gfx pos = getTranslation(t); 
381                 ntlVec3Gfx scale = mcScale.get(t);
382                 ntlVec3Gfx rot = mcRot.get(t);
383                 ntlMat4Gfx rotMat;
384                 rotMat.initRotationXYZ(rot[0],rot[1],rot[2]);
385                 pos += mInitialPos;
386                 //errMsg("ntlGeometryObject::applyTransformation","obj="<<getName()<<" t"<<pos<<" r"<<rot<<" s"<<scale);
387                 for(int i=vstart; i<vend; i++) {
388                         (*verts)[i] *= scale;
389                         (*verts)[i] = rotMat * (*verts)[i];
390                         (*verts)[i] += pos;
391                         //if(i<10) errMsg("ntlGeometryObject::applyTransformation"," v"<<i<<"/"<<vend<<"="<<(*verts)[i]);
392                 }
393                 if(norms) {
394                         for(int i=vstart; i<vend; i++) {
395                                 (*norms)[i] = rotMat * (*norms)[i];
396                         }
397                 }
398         } else {
399                 // not animated, cached points were already returned
400                 //errMsg ("ntlGeometryObject::applyTransformation","Object "<<getName()<<" used cached points ");
401         }
402 }
403
404 /*! init triangle divisions */
405 void ntlGeometryObject::calcTriangleDivs(vector<ntlVec3Gfx> &verts, vector<ntlTriangle> &tris, gfxReal fsTri) {
406         mTriangleDivs1.resize( tris.size() );
407         mTriangleDivs2.resize( tris.size() );
408         mTriangleDivs3.resize( tris.size() );
409
410         //fsTri *= 2.; // DEBUG! , wrong init!
411
412         for(size_t i=0; i<tris.size(); i++) {
413                 const ntlVec3Gfx p0 = verts[ tris[i].getPoints()[0] ];
414                 const ntlVec3Gfx p1 = verts[ tris[i].getPoints()[1] ];
415                 const ntlVec3Gfx p2 = verts[ tris[i].getPoints()[2] ];
416                 const ntlVec3Gfx side1 = p1 - p0;
417                 const ntlVec3Gfx side2 = p2 - p0;
418                 const ntlVec3Gfx side3 = p1 - p2;
419                 int divs1=0, divs2=0, divs3=0;
420                 if(normNoSqrt(side1) > fsTri*fsTri) { divs1 = (int)(norm(side1)/fsTri); }
421                 if(normNoSqrt(side2) > fsTri*fsTri) { divs2 = (int)(norm(side2)/fsTri); }
422
423                 mTriangleDivs1[i] = divs1;
424                 mTriangleDivs2[i] = divs2;
425                 mTriangleDivs3[i] = divs3;
426         }
427 }
428
429 /*! Prepare points for moving objects */
430 void ntlGeometryObject::initMovingPoints(double time, gfxReal featureSize) {
431         if((mMovPntsInited==featureSize)&&(!getMeshAnimated())) return;
432         const bool debugMoinit=false;
433
434         vector<ntlTriangle> triangles; 
435         vector<ntlVec3Gfx> vertices; 
436         vector<ntlVec3Gfx> vnormals; 
437         int objectId = 1;
438         this->getTriangles(time, &triangles,&vertices,&vnormals,objectId);
439         
440         mMovPoints.clear();
441         mMovNormals.clear();
442         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPoints","Object "<<getName()<<" has v:"<<vertices.size()<<" t:"<<triangles.size() );
443         // no points?
444         if(vertices.size()<1) {
445                 mMaxMovPnt=-1;
446                 return; 
447         }
448         ntlVec3f maxscale = channelFindMaxVf(mcScale);
449         float maxpart = ABS(maxscale[0]);
450         if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]);
451         if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]);
452         float scaleFac = 1.0/(maxpart);
453         // TODO - better reinit from time to time?
454         const gfxReal fsTri = featureSize*0.5 *scaleFac;
455         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPoints","maxscale:"<<maxpart<<" featureSize:"<<featureSize<<" fsTri:"<<fsTri );
456
457         if(mTriangleDivs1.size()!=triangles.size()) {
458                 calcTriangleDivs(vertices,triangles,fsTri);
459         }
460
461         // debug: count points to init
462         /*if(debugMoinit) {
463                 errMsg("ntlGeometryObject::initMovingPoints","Object "<<getName()<<" estimating...");
464                 int countp=vertices.size()*2;
465                 for(size_t i=0; i<triangles.size(); i++) {
466                         ntlVec3Gfx p0 = vertices[ triangles[i].getPoints()[0] ];
467                         ntlVec3Gfx side1 = vertices[ triangles[i].getPoints()[1] ] - p0;
468                         ntlVec3Gfx side2 = vertices[ triangles[i].getPoints()[2] ] - p0;
469                         int divs1=0, divs2=0;
470                         if(normNoSqrt(side1) > fsTri*fsTri) { divs1 = (int)(norm(side1)/fsTri); }
471                         if(normNoSqrt(side2) > fsTri*fsTri) { divs2 = (int)(norm(side2)/fsTri); }
472                         errMsg("ntlGeometryObject::initMovingPoints","tri:"<<i<<" p:"<<p0<<" s1:"<<side1<<" s2:"<<side2<<" -> "<<divs1<<","<<divs2 );
473                         if(divs1+divs2 > 0) {
474                                 for(int u=0; u<=divs1; u++) {
475                                         for(int v=0; v<=divs2; v++) {
476                                                 const gfxReal uf = (gfxReal)(u+0.25) / (gfxReal)(divs1+0.0);
477                                                 const gfxReal vf = (gfxReal)(v+0.25) / (gfxReal)(divs2+0.0);
478                                                 if(uf+vf>1.0) continue;
479                                                 countp+=2;
480                                         }
481                                 }
482                         }
483                 }
484                 errMsg("ntlGeometryObject::initMovingPoints","Object "<<getName()<<" requires:"<<countp*2);
485         } // */
486
487         bool discardInflowBack = false;
488         if( (mGeoInitType==FGI_MBNDINFLOW) && (mcInitialVelocity.accessValues().size()<1) ) discardInflowBack = true;
489         discardInflowBack = false; // DEBUG disable for now
490
491
492         // init std points
493         for(size_t i=0; i<vertices.size(); i++) {
494                 ntlVec3Gfx p = vertices[ i ];
495                 ntlVec3Gfx n = vnormals[ i ];
496                 // discard inflow backsides
497                 //if( (mGeoInitType==FGI_MBNDINFLOW) && (!mIsAnimated)) {
498                 if(discardInflowBack) { //if( (mGeoInitType==FGI_MBNDINFLOW) && (!mIsAnimated)) {
499                         if(dot(mInitialVelocity,n)<0.0) continue;
500                 }
501                 mMovPoints.push_back(p);
502                 mMovNormals.push_back(n);
503                 //errMsg("ntlGeometryObject::initMovingPoints","std"<<i<<" p"<<p<<" n"<<n<<" ");
504         }
505         // init points & refine...
506         for(size_t i=0; i<triangles.size(); i++) {
507                 int *trips = triangles[i].getPoints();
508                 const ntlVec3Gfx p0 = vertices[ trips[0] ];
509                 const ntlVec3Gfx side1 = vertices[ trips[1] ] - p0;
510                 const ntlVec3Gfx side2 = vertices[ trips[2] ] - p0;
511                 int divs1=mTriangleDivs1[i], divs2=mTriangleDivs2[i];
512                 
513                 const ntlVec3Gfx trinormOrg = getNormalized(cross(side1,side2));
514                 const ntlVec3Gfx trinorm = trinormOrg*0.25*featureSize;
515                 if(discardInflowBack) { 
516                         if(dot(mInitialVelocity,trinorm)<0.0) continue;
517                 }
518                 //errMsg("ntlGeometryObject::initMovingPoints","Tri1 "<<vertices[trips[0]]<<","<<vertices[trips[1]]<<","<<vertices[trips[2]]<<" "<<divs1<<","<<divs2 );
519                 if(divs1+divs2 > 0) {
520                         for(int u=0; u<=divs1; u++) {
521                                 for(int v=0; v<=divs2; v++) {
522                                         const gfxReal uf = (gfxReal)(u+0.25) / (gfxReal)(divs1+0.0);
523                                         const gfxReal vf = (gfxReal)(v+0.25) / (gfxReal)(divs2+0.0);
524                                         if(uf+vf>1.0) continue;
525                                         ntlVec3Gfx p = 
526                                                 vertices[ trips[0] ] * (1.0-uf-vf)+
527                                                 vertices[ trips[1] ] * uf +
528                                                 vertices[ trips[2] ] * vf;
529                                         //ntlVec3Gfx n = vnormals[ 
530                                                 //trips[0] ] * (1.0-uf-vf)+
531                                                 //vnormals[ trips[1] ]*uf +
532                                                 //vnormals[ trips[2] ]*vf;
533                                         //normalize(n);
534                                         // discard inflow backsides
535
536                                         mMovPoints.push_back(p + trinorm); // NEW!?
537                                         mMovPoints.push_back(p - trinorm);
538                                         mMovNormals.push_back(trinormOrg);
539                                         mMovNormals.push_back(trinormOrg); 
540                                         //errMsg("TRINORM","p"<<p<<" n"<<n<<" trin"<<trinorm);
541                                 }
542                         }
543                 }
544         }
545
546         // find max point
547         mMaxMovPnt = 0;
548         gfxReal dist = normNoSqrt(mMovPoints[0]);
549         for(size_t i=0; i<mMovPoints.size(); i++) {
550                 if(normNoSqrt(mMovPoints[i])>dist) {
551                         mMaxMovPnt = i;
552                         dist = normNoSqrt(mMovPoints[0]);
553                 }
554         }
555
556         if(    (this-getMeshAnimated())
557       || (mcTrans.accessValues().size()>1)  // VALIDATE
558             || (mcRot.accessValues().size()>1) 
559             || (mcScale.accessValues().size()>1) 
560                 ) {
561                 // also do trafo...
562         } else {
563                 mCachedMovPoints = mMovPoints;
564                 mCachedMovNormals = mMovNormals;
565                 //applyTransformation(time, &mCachedMovPoints, &mCachedMovNormals, 0, mCachedMovPoints.size(), true);
566                 applyTransformation(time, &mCachedMovPoints, NULL, 0, mCachedMovPoints.size(), true);
567                 mHaveCachedMov = true;
568                 debMsgStd("ntlGeometryObject::initMovingPoints",DM_MSG,"Object "<<getName()<<" cached points ", 7);
569         }
570
571         mMovPntsInited = featureSize;
572         debMsgStd("ntlGeometryObject::initMovingPoints",DM_MSG,"Object "<<getName()<<" inited v:"<<vertices.size()<<"->"<<mMovPoints.size() , 5);
573 }
574 /*! Prepare points for animated objects,
575  * init both sets, never used cached points 
576  * discardInflowBack ignore */
577 void ntlGeometryObject::initMovingPointsAnim(
578                  double srctime, vector<ntlVec3Gfx> &srcmovPoints,
579                  double dsttime, vector<ntlVec3Gfx> &dstmovPoints,
580                  vector<ntlVec3Gfx> *dstmovNormals,
581                  gfxReal featureSize,
582                  ntlVec3Gfx geostart, ntlVec3Gfx geoend
583                  ) {
584         const bool debugMoinit=false;
585
586         vector<ntlTriangle> srctriangles; 
587         vector<ntlVec3Gfx> srcvertices; 
588         vector<ntlVec3Gfx> unused_normals; 
589         vector<ntlTriangle> dsttriangles; 
590         vector<ntlVec3Gfx> dstvertices; 
591         vector<ntlVec3Gfx> dstnormals; 
592         int objectId = 1;
593         // TODO optimize? , get rid of normals?
594         unused_normals.clear();
595         this->getTriangles(srctime, &srctriangles,&srcvertices,&unused_normals,objectId);
596         unused_normals.clear();
597         this->getTriangles(dsttime, &dsttriangles,&dstvertices,&dstnormals,objectId);
598         
599         srcmovPoints.clear();
600         dstmovPoints.clear();
601         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPointsAnim","Object "<<getName()<<" has srcv:"<<srcvertices.size()<<" srct:"<<srctriangles.size() );
602         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPointsAnim","Object "<<getName()<<" has dstv:"<<dstvertices.size()<<" dstt:"<<dsttriangles.size() );
603         // no points?
604         if(srcvertices.size()<1) {
605                 mMaxMovPnt=-1;
606                 return; 
607         }
608         if((srctriangles.size() != dsttriangles.size()) ||
609            (srcvertices.size() != dstvertices.size()) ) {
610                 errMsg("ntlGeometryObject::initMovingPointsAnim","Invalid triangle numbers! Aborting...");
611                 return;
612         }
613         ntlVec3f maxscale = channelFindMaxVf(mcScale);
614         float maxpart = ABS(maxscale[0]);
615         if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]);
616         if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]);
617         float scaleFac = 1.0/(maxpart);
618         // TODO - better reinit from time to time?
619         const gfxReal fsTri = featureSize*0.5 *scaleFac;
620         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPointsAnim","maxscale:"<<maxpart<<" featureSize:"<<featureSize<<" fsTri:"<<fsTri );
621
622         if(mTriangleDivs1.size()!=srctriangles.size()) {
623                 calcTriangleDivs(srcvertices,srctriangles,fsTri);
624         }
625
626
627         // init std points
628         for(size_t i=0; i<srcvertices.size(); i++) {
629                 srcmovPoints.push_back(srcvertices[i]);
630                 //srcmovNormals.push_back(srcnormals[i]);
631         }
632         for(size_t i=0; i<dstvertices.size(); i++) {
633                 dstmovPoints.push_back(dstvertices[i]);
634                 if(dstmovNormals) (*dstmovNormals).push_back(dstnormals[i]);
635         }
636         if(debugMoinit) errMsg("ntlGeometryObject::initMovingPointsAnim","stats src:"<<srcmovPoints.size()<<" dst:"<<dstmovPoints.size()<<" " );
637         // init points & refine...
638         for(size_t i=0; i<srctriangles.size(); i++) {
639                 const int divs1=mTriangleDivs1[i];
640                 const int       divs2=mTriangleDivs2[i];
641                 if(divs1+divs2 > 0) {
642                         int *srctrips = srctriangles[i].getPoints();
643                         int *dsttrips = dsttriangles[i].getPoints();
644                         const ntlVec3Gfx srcp0 =    srcvertices[ srctrips[0] ];
645                         const ntlVec3Gfx srcside1 = srcvertices[ srctrips[1] ] - srcp0;
646                         const ntlVec3Gfx srcside2 = srcvertices[ srctrips[2] ] - srcp0;
647                         const ntlVec3Gfx dstp0 =    dstvertices[ dsttrips[0] ];
648                         const ntlVec3Gfx dstside1 = dstvertices[ dsttrips[1] ] - dstp0;
649                         const ntlVec3Gfx dstside2 = dstvertices[ dsttrips[2] ] - dstp0;
650                         const ntlVec3Gfx src_trinorm    = getNormalized(cross(srcside1,srcside2))*0.25*featureSize;
651                         const ntlVec3Gfx dst_trinormOrg = getNormalized(cross(dstside1,dstside2));
652                         const ntlVec3Gfx dst_trinorm    = dst_trinormOrg                         *0.25*featureSize;
653                         //errMsg("ntlGeometryObject::initMovingPointsAnim","Tri1 "<<srcvertices[srctrips[0]]<<","<<srcvertices[srctrips[1]]<<","<<srcvertices[srctrips[2]]<<" "<<divs1<<","<<divs2 );
654                         for(int u=0; u<=divs1; u++) {
655                                 for(int v=0; v<=divs2; v++) {
656                                         const gfxReal uf = (gfxReal)(u+0.25) / (gfxReal)(divs1+0.0);
657                                         const gfxReal vf = (gfxReal)(v+0.25) / (gfxReal)(divs2+0.0);
658                                         if(uf+vf>1.0) continue;
659                                         ntlVec3Gfx srcp = 
660                                                 srcvertices[ srctrips[0] ] * (1.0-uf-vf)+
661                                                 srcvertices[ srctrips[1] ] * uf +
662                                                 srcvertices[ srctrips[2] ] * vf;
663                                         ntlVec3Gfx dstp = 
664                                                 dstvertices[ dsttrips[0] ] * (1.0-uf-vf)+
665                                                 dstvertices[ dsttrips[1] ] * uf +
666                                                 dstvertices[ dsttrips[2] ] * vf;
667
668                                         // cutoffDomain
669                                         if((srcp[0]<geostart[0]) && (dstp[0]<geostart[0])) continue;
670                                         if((srcp[1]<geostart[1]) && (dstp[1]<geostart[1])) continue;
671                                         if((srcp[2]<geostart[2]) && (dstp[2]<geostart[2])) continue;
672                                         if((srcp[0]>geoend[0]  ) && (dstp[0]>geoend[0]  )) continue;
673                                         if((srcp[1]>geoend[1]  ) && (dstp[1]>geoend[1]  )) continue;
674                                         if((srcp[2]>geoend[2]  ) && (dstp[2]>geoend[2]  )) continue;
675                                         
676                                         srcmovPoints.push_back(srcp+src_trinorm); // SURFENHTEST
677                                         srcmovPoints.push_back(srcp-src_trinorm);
678
679                                         dstmovPoints.push_back(dstp+dst_trinorm); // SURFENHTEST
680                                         dstmovPoints.push_back(dstp-dst_trinorm);
681                                         if(dstmovNormals) {
682                                                 (*dstmovNormals).push_back(dst_trinormOrg);
683                                                 (*dstmovNormals).push_back(dst_trinormOrg); }
684                                 }
685                         }
686                 }
687         }
688
689         // find max point not necessary
690         debMsgStd("ntlGeometryObject::initMovingPointsAnim",DM_MSG,"Object "<<getName()<<" inited v:"<<srcvertices.size()<<"->"<<srcmovPoints.size()<<","<<dstmovPoints.size() , 5);
691 }
692
693 /*! Prepare points for moving objects */
694 void ntlGeometryObject::getMovingPoints(vector<ntlVec3Gfx> &ret, vector<ntlVec3Gfx> *norms) {
695         if(mHaveCachedMov) {
696                 ret = mCachedMovPoints;
697                 if(norms) { 
698                         *norms = mCachedMovNormals; 
699                         //errMsg("ntlGeometryObject","getMovingPoints - Normals currently unused!");
700                 }
701                 //errMsg ("ntlGeometryObject::getMovingPoints","Object "<<getName()<<" used cached points "); // DEBUG
702                 return;
703         }
704
705         ret = mMovPoints;
706         if(norms) { 
707                 //errMsg("ntlGeometryObject","getMovingPoints - Normals currently unused!");
708                 *norms = mMovNormals; 
709         }
710 }
711
712
713 /*! Calculate max. velocity on object from t1 to t2 */
714 ntlVec3Gfx ntlGeometryObject::calculateMaxVel(double t1, double t2) {
715         ntlVec3Gfx vel(0.);
716         if(mMaxMovPnt<0) return vel;
717                 
718         vector<ntlVec3Gfx> verts1,verts2;
719         verts1.push_back(mMovPoints[mMaxMovPnt]);
720         verts2 = verts1;
721         applyTransformation(t1,&verts1,NULL, 0,verts1.size(), true);
722         applyTransformation(t2,&verts2,NULL, 0,verts2.size(), true);
723
724         vel = (verts2[0]-verts1[0]); // /(t2-t1);
725         errMsg("ntlGeometryObject::calculateMaxVel","t1="<<t1<<" t2="<<t2<<" p1="<<verts1[0]<<" p2="<<verts2[0]<<" v="<<vel);
726         return vel;
727 }
728
729 /*! get translation at time t*/
730 ntlVec3Gfx ntlGeometryObject::getTranslation(double t) {
731         ntlVec3Gfx pos = mcTrans.get(t);
732   // DEBUG CP_FORCECIRCLEINIT 1
733         /*if( 
734                         (mName.compare(string("0__ts1"))==0) ||
735                         (mName.compare(string("1__ts1"))==0) ||
736                         (mName.compare(string("2__ts1"))==0) ||
737                         (mName.compare(string("3__ts1"))==0) ||
738                         (mName.compare(string("4__ts1"))==0) ||
739                         (mName.compare(string("5__ts1"))==0) ||
740                         (mName.compare(string("6__ts1"))==0) ||
741                         (mName.compare(string("7__ts1"))==0) ||
742                         (mName.compare(string("8__ts1"))==0) ||
743                         (mName.compare(string("9__ts1"))==0) 
744                         ) { int j=mName[0]-'0';
745                         ntlVec3Gfx ppos(0.); { // DEBUG
746                         const float tscale=10.;
747                         const float tprevo = 0.33;
748                         const ntlVec3Gfx   toff(50,50,0);
749                         const ntlVec3Gfx oscale(30,30,0);
750                         ppos[0] =  cos(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[0] + toff[0];
751                         ppos[1] = -sin(tscale* t - tprevo*(float)j + M_PI -0.1) * oscale[1] + toff[1];
752                         ppos[2] =                               toff[2]; } // DEBUG
753                         pos = ppos;
754                         pos[2] = 0.15;
755         }
756   // DEBUG CP_FORCECIRCLEINIT 1 */
757         return pos;
758 }
759 /*! get active flag time t*/
760 float ntlGeometryObject::getGeoActive(double t) {
761         //float act = mcGeoActive.getConstant(t);
762         float act = mcGeoActive.get(t); // if <= 0.0 -> off
763         return act;
764 }
765
766 void ntlGeometryObject::setInitialVelocity(ntlVec3Gfx set) { 
767         mInitialVelocity=set; 
768         mcInitialVelocity = AnimChannel<ntlVec3Gfx>(set); 
769 }
770 ntlVec3Gfx ntlGeometryObject::getInitialVelocity(double t) { 
771         ntlVec3Gfx v =  mcInitialVelocity.get(t); //return mInitialVelocity; 
772         if(!mLocalCoordInivel) return v;
773
774         ntlVec3Gfx rot = mcRot.get(t);
775         ntlMat4Gfx rotMat;
776         rotMat.initRotationXYZ(rot[0],rot[1],rot[2]);
777         v = rotMat * v;
778         return v;
779 }
780         
781