File: CapillarityEngine.cpp

package info (click to toggle)
yade 2026.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 34,448 kB
  • sloc: cpp: 97,645; python: 52,173; sh: 677; makefile: 162
file content (594 lines) | stat: -rw-r--r-- 24,574 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*************************************************************************
*  Copyright (C) 2013 by Bruno Chareyre    <bruno.chareyre@grenoble-inp.fr>  *
*                                                                        *
*  This program is free software; it is licensed under the terms of the  *
*  GNU General Public License v2 or later. See file LICENSE for details. *
*************************************************************************/

#ifdef YADE_CGAL

#include <pkg/common/ElastMat.hpp>
#include <pkg/dem/CapillarityEngine.hpp>

#include <lib/base/Math.hpp>
#include <lib/high-precision/Constants.hpp>
#include <lib/high-precision/MathApprox.hpp>
#include <core/Omega.hpp>
#include <core/Scene.hpp>
#include <pkg/dem/HertzMindlin.hpp>
#include <pkg/dem/ScGeom.hpp>
#include <fstream>
#include <iostream>

namespace yade { // Cannot have #include directive inside.

YADE_PLUGIN((CapillarityEngine));

DelaunayInterpolator::Dt          CapillarityEngine::dtVbased;
DelaunayInterpolator::Dt          CapillarityEngine::dtPbased;
std::vector<MeniscusPhysicalData> CapillarityEngine::solutions;
const unsigned                    DelaunayInterpolator::comb[] = { 1, 2, 3, 0, 1, 2 };

Real CapillarityEngine::intEnergy()
{
	Real energy = 0;
	FOREACH(const shared_ptr<Interaction>& I, *scene->interactions)
	{
		if (!I->isReal()) continue;
		ScGeom*                currentGeometry = static_cast<ScGeom*>(I->geom.get());
		CapillaryPhysDelaunay* phys            = static_cast<CapillaryPhysDelaunay*>(I->phys.get());
		if (phys) {
			if (phys->SInterface != 0) {
				energy += liquidTension
				        * (phys->SInterface - 4 * Mathr::PI * (pow(currentGeometry->radius1, 2))
				           - 4 * Mathr::PI * (pow(currentGeometry->radius2, 2)));
			}
		}
	}
	return energy;
}


Real CapillarityEngine::wnInterface()
{
	Real wn = 0;
	FOREACH(const shared_ptr<Interaction>& I, *scene->interactions)
	{
		if (!I->isReal()) continue;
		ScGeom*                currentGeometry = static_cast<ScGeom*>(I->geom.get());
		CapillaryPhysDelaunay* phys            = static_cast<CapillaryPhysDelaunay*>(I->phys.get());
		if (phys) {
			if (phys->SInterface != 0) {
				wn += (phys->SInterface
				       - 2 * Mathr::PI
				               * (pow(currentGeometry->radius1, 2) * (1 + cos(phys->Delta1))
				                  + pow(currentGeometry->radius2, 2) * (1 + cos(phys->Delta2))));
			}
		}
	}
	return wn;
}

Real CapillarityEngine::swInterface()
{
	Real sw = 0;
	FOREACH(const shared_ptr<Interaction>& I, *scene->interactions)
	{
		if (!I->isReal()) continue;
		ScGeom*                currentGeometry = static_cast<ScGeom*>(I->geom.get());
		CapillaryPhysDelaunay* phys            = static_cast<CapillaryPhysDelaunay*>(I->phys.get());
		if (phys) {
			sw += (2 * Mathr::PI
			       * (pow(currentGeometry->radius1, 2) * (1 - cos(phys->Delta1)) + pow(currentGeometry->radius2, 2) * (1 - cos(phys->Delta2))));
		}
	}
	return sw;
}


Real CapillarityEngine::waterVolume()
{
	Real volume = 0;
	FOREACH(const shared_ptr<Interaction>& I, *scene->interactions)
	{
		if (!I->isReal()) continue;
		CapillaryPhysDelaunay* phys = static_cast<CapillaryPhysDelaunay*>(I->phys.get());
		if (phys) { volume += phys->vMeniscus; }
	}
	return volume;
}

void CapillarityEngine::triangulateData()
{
	/// We get data from a file and input them in triangulations
	if (solutions.size() > 0) {
		LOG_WARN("CapillarityEngine asking triangulation for the second time. Ignored.");
		return;
	}
	std::ifstream file(inputFilename.c_str());
	if (!file.is_open()) {
		LOG_ERROR("No data file found for capillary law. Check path and inputFilename.");
		return;
	}

	MeniscusPhysicalData dat;
	double               ending;
	while (file.good()) {
		file >> dat.succion >> dat.force >> dat.distance >> dat.volume >> dat.surface >> dat.arcLength >> dat.delta1 >> dat.delta2 >> dat.R >> ending;
		dat.ending = (bool)ending;
		solutions.push_back(dat);
	}
	file.close();
	// Make lists of points with index, so we can use range insertion, more efficient
	// see http://doc.cgal.org/latest/Triangulation_3/index.html#Triangulation_3SettingInformationWhileInserting
	std::vector<std::pair<K::Point_3, unsigned>> pointsP, pointsV;
	for (unsigned int k = 0; k < solutions.size(); k++) {
		pointsP.push_back(std::make_pair(K::Point_3(solutions[k].R, solutions[k].succion, solutions[k].distance), k));
		pointsV.push_back(std::make_pair(K::Point_3(solutions[k].R, solutions[k].volume, solutions[k].distance), k));
	}
	// and now range insertion
	dtPbased.insert(pointsP.begin(), pointsP.end());
	dtVbased.insert(pointsV.begin(), pointsV.end());
}

int firstIteration = 1;
int xShadow        = 0;

template <
        typename IPhysT> // the template parameter should be an IPhys with capillary attributes, see the selection of correct type below, in CapillarityEngine::action()
void CapillarityEngine::solveBridgesT(Real suction, bool reset)
{
	if (!scene) cerr << "scene not defined!";
	shared_ptr<BodyContainer>& bodies = scene->bodies;
	if (dtPbased.number_of_vertices() < 1) triangulateData();
	if (dtPbased.number_of_vertices() < 1) return; //something went wrong, probably no input files, return
	if (fusionDetection && !bodiesMenisciiList.initialized) bodiesMenisciiList.prepare(scene);
	timingDeltas->checkpoint("init solver");

	const long size = scene->interactions->size();
#ifdef YADE_OPENMP
#pragma omp parallel for schedule(guided) num_threads(ompThreads > 0 ? std::min(ompThreads, omp_get_max_threads()) : omp_get_max_threads())
#endif
	for (long i = 0; i < size; i++) {
		const shared_ptr<Interaction>& interaction = (*scene->interactions)[i];
		auto                           phys        = static_cast<IPhysT*>(interaction->phys.get());

		if (interaction->isReal() /*&& phys->computeBridge == true FIXME: not available in Mindlin */) {
			const unsigned int& id1 = interaction->getId1();
			const unsigned int& id2 = interaction->getId2();

			/// interaction geometry search (this test is to compute capillarity only between spheres (probably a better way to do that)
			const int& geometryIndex1 = (*bodies)[id1]->shape->getClassIndex(); // !!!
			const int& geometryIndex2 = (*bodies)[id2]->shape->getClassIndex();
			/// definition of interacting objects (not necessarily in contact)
			ScGeom* currentContactGeometry = static_cast<ScGeom*>(interaction->geom.get());

			if (!(geometryIndex1 == geometryIndex2)) {
				if (currentContactGeometry->penetrationDepth < 0) scene->interactions->requestErase(interaction);
				continue;
			}

			/// Interacting Grains:
			// If you want to define a ratio between YADE sphere size and real sphere size
			Real alpha = 1;
			Real R1    = alpha * std::max(currentContactGeometry->radius2, currentContactGeometry->radius1);
			Real R2    = alpha * std::min(currentContactGeometry->radius2, currentContactGeometry->radius1);

			/// intergranular distance
			Real D = -alpha * ((currentContactGeometry->penetrationDepth) + epsilonMean * (R1 + R2));

			bool wasMeniscus = phys->meniscus;
			if (D <= 0 || createDistantMeniscii) {
				if (fusionDetection && !phys->meniscus) bodiesMenisciiList.insert(interaction);
				phys->meniscus = true;
			}
			Real Dinterpol = D / R1;

			/// Suction (Capillary pressure):
			if (imposePressure || (!imposePressure && totalVolumeConstant)) {
				Real Pinterpol          = 0;
				Pinterpol               = phys->isBroken ? 0 : suction * R1 / liquidTension;
				phys->capillaryPressure = suction;
				/// Capillary solution finder:
				if ((Pinterpol >= 0) && phys->meniscus) {
					// NOTE: here, the parameter phys->m will be missing for MindlinCapillaryPhys, or CapillaryPhys
					// Possible solution for merging the capillary flavors: give the same name to CapillaryPhysDelaunay::m  and CapillaryPhys::currentIndexes
					// and make the interpolator a template parameter of this entire function, one interpolator will use a cell handle (from phys->m) or table indices (from CapillaryPhys)
					MeniscusPhysicalData solution = DelaunayInterpolator::interpolate1(
					        dtPbased, K::Point_3(R2 / R1, Pinterpol, Dinterpol), phys->m, solutions, reset);
					/// capillary adhesion force
					Real Finterpol = solution.force;
					phys->fCap     = Finterpol * R1 * liquidTension * currentContactGeometry->normal;
					/// meniscus volume
					phys->vMeniscus = solution.volume * pow(R1, 3);

					if (phys->vMeniscus > 0) {
						phys->meniscus   = true;
						phys->SInterface = solution.surface * pow(R1, 2);
					} else {
						phys->meniscus   = false;
						phys->SInterface = 4 * Mathr::PI * (pow(R1, 2) + pow(R2, 2));
						if (fusionDetection and wasMeniscus) bodiesMenisciiList.remove(interaction);
						if (currentContactGeometry->penetrationDepth < 0) scene->interactions->requestErase(interaction);
						continue;
					}
					/// wetting angles
					phys->Delta1 = math::max(solution.delta1, solution.delta2);
					phys->Delta2 = math::min(solution.delta1, solution.delta2);
				} else
					scene->interactions->requestErase(interaction);

			} else {
				if (phys->vMeniscus == 0 and phys->capillaryPressure != 0) { //FIXME: test capillaryPressure consistently (!0 or >0 or >=0?!)
					Real Pinterpol = 0;
					Pinterpol      = phys->isBroken ? 0 : phys->capillaryPressure * R1 / liquidTension;
					if ((Pinterpol >= 0) && phys->meniscus) {
						MeniscusPhysicalData solution = DelaunayInterpolator::interpolate1(
						        dtPbased, K::Point_3(R2 / R1, Pinterpol, Dinterpol), phys->m, solutions, reset);
						/// capillary adhesion force
						phys->fCap = solution.force * R1 * liquidTension * currentContactGeometry->normal;
						/// meniscus volume
						Real Vinterpol   = solution.volume * pow(R1, 3);
						Real SInterface  = solution.surface * pow(R1, 2);
						phys->vMeniscus  = Vinterpol;
						phys->SInterface = SInterface;
						if (Vinterpol > 0) phys->meniscus = true;
						else
							phys->meniscus = false;

						if (phys->meniscus == false) phys->SInterface = 4 * Mathr::PI * (pow(R1, 2)) + 4 * Mathr::PI * (pow(R2, 2));
						if (!Vinterpol) {
							if (fusionDetection || phys->isBroken) bodiesMenisciiList.remove(interaction);
							if (D > ((interactionDetectionFactor - 1)
							         * (currentContactGeometry->radius2 + currentContactGeometry->radius1)))
								scene->interactions->requestErase(interaction);
						}
						/// wetting angles
						phys->Delta1 = math::max(solution.delta1, solution.delta2);
						phys->Delta2 = math::min(solution.delta1, solution.delta2);
					}
				} else {
					Real Vinterpol = phys->vMeniscus / pow(R1, 3);
					/// Capillary solution finder:
					if (phys->meniscus) {
						MeniscusPhysicalData solution = DelaunayInterpolator::interpolate1(
						        dtVbased, K::Point_3(R2 / R1, Vinterpol, Dinterpol), phys->m, solutions, reset);
						/// capillary adhesion force
						Real     Finterpol = solution.force;
						Vector3r fCap      = Finterpol * R1 * liquidTension * currentContactGeometry->normal;
						phys->fCap         = fCap;
						/// suction and interfacial area
						Real Pinterpol          = solution.succion * liquidTension / R1;
						Real SInterface         = solution.surface * pow(R1, 2);
						phys->capillaryPressure = Pinterpol;
						phys->SInterface        = SInterface;
						if (Finterpol > 0) phys->meniscus = true;
						else {
							phys->vMeniscus = 0;
							phys->meniscus  = false;
						}
						if (!Vinterpol) {
							if ((fusionDetection) || phys->isBroken) bodiesMenisciiList.remove(interaction);
							if (D > ((interactionDetectionFactor - 1)
							         * (currentContactGeometry->radius2 + currentContactGeometry->radius1)))
								scene->interactions->requestErase(interaction);
						}
						/// wetting angles
						phys->Delta1 = math::max(solution.delta1, solution.delta2);
						phys->Delta2 = math::min(solution.delta1, solution.delta2);
					}
				}
			}
			///interaction is not real //If the interaction is not real, it should not be in the list
		} else {
			if (fusionDetection) bodiesMenisciiList.remove(interaction);
			scene->interactions->requestErase(interaction);
		}
	}
	timingDeltas->checkpoint("compute all");
	if (fusionDetection) checkFusion();
	timingDeltas->checkpoint("check fusion");
	createDistantMeniscii = false;
}

shared_ptr<CapillaryPhysDelaunay> CapillarityEngine::solveStandalone(
        Real R1, Real R2, Real pressure, Real gap, shared_ptr<CapillaryPhysDelaunay> bridge = shared_ptr<CapillaryPhysDelaunay>() /*, bool pBased = true*/)
{
	if (dtPbased.number_of_vertices() < 1) triangulateData();
	if (not bridge) bridge = shared_ptr<CapillaryPhysDelaunay>(new CapillaryPhysDelaunay());
	if (dtPbased.number_of_vertices() < 1) return bridge; //something went wrong, probably no input files, return

	Real Dinterpol = gap / R1;
	Real Pinterpol = pressure * R1 / liquidTension;

	MeniscusPhysicalData solution = DelaunayInterpolator::interpolate1(dtPbased, K::Point_3(R2 / R1, Pinterpol, Dinterpol), bridge->m, solutions, false);
	bridge->fCap                  = solution.force * Vector3r(1, 0, 0);
	bridge->vMeniscus             = solution.volume * pow(R1, 3);
	bridge->SInterface            = solution.surface * pow(R1, 2);
	bridge->meniscus              = solution.volume > 0;
	return bridge;
}

void CapillarityEngine::checkPhysType()
{
	// TODO: add more options here if we want more contact models compatible with capillarity
	// NOTE: We are assuming that only one type at a time is used in one simulation here
	for (auto ii = scene->interactions->begin(); ii != scene->interactions->end(); ++ii) {
		if (not(*ii)->phys) continue;
		if (CapillaryPhysDelaunay::getClassIndexStatic() == (*ii)->phys->getClassIndex()) {
			hertzOn          = false;
			hertzInitialized = true;
			break;
		} else if (MindlinCapillaryPhys::getClassIndexStatic() == (*ii)->phys->getClassIndex()) {
			hertzOn          = true;
			hertzInitialized = true;
			break;
		}
	}
	if (not hertzInitialized) LOG_ERROR("The capillary law is not implemented for the interaction physics used here, or no interactions were found.")
}


void CapillarityEngine::action()
{
	timingDeltas->start();
	if (fusionDetection and ompThreads > 1) {
		LOG_WARN("Fusion detection is not thread-safe. Turning ompThreads=1. (It is in fact 'most-likely' unsafe, not tested, comment-out this check "
		         "if you want to see by yourself)")
		ompThreads = 1;
	}
	if (!hertzInitialized) checkPhysType();
	bool switched = (pressureBased != (imposePressure or totalVolumeConstant));
	pressureBased = (imposePressure or totalVolumeConstant);

	void (CapillarityEngine::*solveBridges)(Real capillaryPressure, bool switched);
	solveBridges = hertzOn ? &CapillarityEngine::solveBridgesT<CapillaryMindlinPhysDelaunay> : &CapillarityEngine::solveBridgesT<CapillaryPhysDelaunay>;

	if (imposePressure) {
		(this->*solveBridges)(capillaryPressure, switched);
	} else {
		if (((totalVolumeConstant || (!totalVolumeConstant && firstIteration == 1)) && totalVolumeofWater != -1)
		    || (totalVolumeConstant && totalVolumeofWater == -1)) {
			if (!totalVolumeConstant) xShadow = 1;
			totalVolumeConstant = 1;
			Real p0             = capillaryPressure;
			Real slope;
			Real eps = 0.0000000001;
			(this->*solveBridges)(p0, switched);
			Real V0 = waterVolume();
			if (totalVolumeConstant && totalVolumeofWater == -1 && firstIteration == 1) {
				totalVolumeofWater = V0;
				firstIteration += 1;
			}
			Real p1 = capillaryPressure + 0.1;
			(this->*solveBridges)(p1, switched);
			Real V1 = waterVolume();
			while (abs((totalVolumeofWater - V1) / totalVolumeofWater) > eps) {
				slope = (p1 - p0) / (V1 - V0);
				p0    = p1;
				V0    = V1;
				p1    = p1 - slope * (V1 - totalVolumeofWater);
				if (p1 < 0) {
					cout << "The requested volume of water is quite big, the simulation will continue at constant suction.:" << p0 << endl;
					capillaryPressure = p0;
					imposePressure    = 1;
					break;
				}
				(this->*solveBridges)(p1, switched);
				V1                = waterVolume();
				capillaryPressure = p1;
			}
			if (xShadow == 1) {
				totalVolumeConstant = 0;
				firstIteration += 1;
			}
		} else {
			if ((!totalVolumeConstant && firstIteration == 1) && totalVolumeofWater == -1) {
				totalVolumeConstant = 1;
				(this->*solveBridges)(capillaryPressure, switched);
				firstIteration += 1;
				totalVolumeConstant = 0;
			} else {
				(this->*solveBridges)(capillaryPressure, switched);
			}
		}
		timingDeltas->checkpoint("closing loop");
	}

	const long size = scene->interactions->size();
#ifdef YADE_OPENMP
#pragma omp parallel for schedule(guided) num_threads(ompThreads > 0 ? std::min(ompThreads, omp_get_max_threads()) : omp_get_max_threads())
#endif
	for (long i = 0; i < size; i++) {
		const shared_ptr<Interaction>& I    = (*scene->interactions)[i];
		CapillaryPhysDelaunay*         phys = static_cast<CapillaryPhysDelaunay*>(I->phys.get());
		if (I->isReal() && phys->computeBridge == true) {
			CapillaryPhysDelaunay* cundallContactPhysics = NULL;
			MindlinCapillaryPhys*  mindlinContactPhysics = NULL;
			if (!hertzOn) cundallContactPhysics = static_cast<CapillaryPhysDelaunay*>(I->phys.get()); //use CapillaryPhysDelaunay for linear model
			else
				mindlinContactPhysics = static_cast<MindlinCapillaryPhys*>(I->phys.get()); //use MindlinCapillaryPhys for hertz model

			if ((hertzOn && mindlinContactPhysics->meniscus) || (!hertzOn && cundallContactPhysics->meniscus)) {
				if (fusionDetection) { //version with effect of fusion
					               //BINARY VERSION : if fusionNumber!=0 then no capillary force
					short int& fusionNumber = hertzOn ? mindlinContactPhysics->fusionNumber : cundallContactPhysics->fusionNumber;
					if (binaryFusion) {
						if (fusionNumber != 0) { //cerr << "fusion" << endl;
							hertzOn ? mindlinContactPhysics->fCap : cundallContactPhysics->fCap = Vector3r::Zero();
							continue;
						}
					}
					//LINEAR VERSION : capillary force is divided by (fusionNumber + 1) - NOTE : any decreasing function of fusionNumber can be considered in fact
					else if (fusionNumber != 0)
						hertzOn ? mindlinContactPhysics->fCap : cundallContactPhysics->fCap /= (fusionNumber + 1.);
				}
				scene->forces.addForce(I->getId1(), hertzOn ? mindlinContactPhysics->fCap : cundallContactPhysics->fCap);
				scene->forces.addForce(I->getId2(), -(hertzOn ? mindlinContactPhysics->fCap : cundallContactPhysics->fCap));
			}
		}
	}
	timingDeltas->checkpoint("addForces");
}
void CapillarityEngine::checkFusion()
{
	//Reset fusion numbers
	InteractionContainer::iterator ii    = scene->interactions->begin();
	InteractionContainer::iterator iiEnd = scene->interactions->end();
	for (; ii != iiEnd; ++ii) {
		if ((*ii)->isReal()) {
			if (!hertzOn) static_cast<CapillaryPhysDelaunay*>((*ii)->phys.get())->fusionNumber = 0;
			else
				static_cast<MindlinCapillaryPhys*>((*ii)->phys.get())->fusionNumber = 0;
		}
	}
	std::list<shared_ptr<Interaction>>::iterator firstMeniscus, lastMeniscus, currentMeniscus;
	Real                                         angle1 = -1.0;
	Real                                         angle2 = -1.0;

	for (int i = 0; i < bodiesMenisciiList.size(); ++i) { // i is the index (or id) of the body being tested
		CapillaryPhysDelaunay* cundallInteractionPhysics1 = NULL;
		MindlinCapillaryPhys*  mindlinInteractionPhysics1 = NULL;
		CapillaryPhysDelaunay* cundallInteractionPhysics2 = NULL;
		MindlinCapillaryPhys*  mindlinInteractionPhysics2 = NULL;
		if (!bodiesMenisciiList[i].empty()) {
			lastMeniscus = bodiesMenisciiList[i].end();
			for (firstMeniscus = bodiesMenisciiList[i].begin(); firstMeniscus != lastMeniscus;
			     ++firstMeniscus) { //FOR EACH MENISCUS ON THIS BODY...
				currentMeniscus = firstMeniscus;
				++currentMeniscus;
				if (!hertzOn) {
					cundallInteractionPhysics1 = YADE_CAST<CapillaryPhysDelaunay*>((*firstMeniscus)->phys.get());
					if (i == (*firstMeniscus)->getId1()) angle1 = cundallInteractionPhysics1->Delta1; //get angle of meniscus1 on body i
					else
						angle1 = cundallInteractionPhysics1->Delta2;
				} else {
					mindlinInteractionPhysics1 = YADE_CAST<MindlinCapillaryPhys*>((*firstMeniscus)->phys.get());
					if (i == (*firstMeniscus)->getId1()) angle1 = mindlinInteractionPhysics1->Delta1; //get angle of meniscus1 on body i
					else
						angle1 = mindlinInteractionPhysics1->Delta2;
				}
				for (; currentMeniscus != lastMeniscus; ++currentMeniscus) { //... CHECK FUSION WITH ALL OTHER MENISCII ON THE BODY
					if (!hertzOn) {
						cundallInteractionPhysics2 = YADE_CAST<CapillaryPhysDelaunay*>((*currentMeniscus)->phys.get());
						if (i == (*currentMeniscus)->getId1())
							angle2 = cundallInteractionPhysics2->Delta1; //get angle of meniscus2 on body i
						else
							angle2 = cundallInteractionPhysics2->Delta2;
					} else {
						mindlinInteractionPhysics2 = YADE_CAST<MindlinCapillaryPhys*>((*currentMeniscus)->phys.get());
						if (i == (*currentMeniscus)->getId1())
							angle2 = mindlinInteractionPhysics2->Delta1; //get angle of meniscus2 on body i
						else
							angle2 = mindlinInteractionPhysics2->Delta2;
					}
					if (angle1 == 0 || angle2 == 0) cerr << "THIS SHOULD NOT HAPPEN!!" << endl;

					Vector3r normalFirstMeniscus   = YADE_CAST<ScGeom*>((*firstMeniscus)->geom.get())->normal;
					Vector3r normalCurrentMeniscus = YADE_CAST<ScGeom*>((*currentMeniscus)->geom.get())->normal;

					Real normalDot = 0;
					if ((*firstMeniscus)->getId1() == (*currentMeniscus)->getId1()
					    || (*firstMeniscus)->getId2() == (*currentMeniscus)->getId2())
						normalDot = normalFirstMeniscus.dot(normalCurrentMeniscus);
					else
						normalDot = -(normalFirstMeniscus.dot(normalCurrentMeniscus));

					Real normalAngle = 0;
					if (normalDot >= 0) normalAngle = math::fastInvCos0(normalDot);
					else
						normalAngle = ((Mathr::PI)-math::fastInvCos0(-(normalDot)));

					if ((angle1 + angle2) * Mathr::DEG_TO_RAD > normalAngle) {
						if (!hertzOn) {
							++(cundallInteractionPhysics1->fusionNumber); //count +1 if 2 meniscii are overlaping
							++(cundallInteractionPhysics2->fusionNumber);
						} else {
							++(mindlinInteractionPhysics1->fusionNumber);
							++(mindlinInteractionPhysics2->fusionNumber);
						}
					};
				}
			}
		}
	}
}


BodiesMenisciiList1::BodiesMenisciiList1(Scene* scene)
{
	initialized = false;
	prepare(scene);
}

bool BodiesMenisciiList1::prepare(Scene* scene)
{
	interactionsOnBody.clear();
	shared_ptr<BodyContainer>& bodies = scene->bodies;

	Body::id_t              MaxId = -1;
	BodyContainer::iterator bi    = bodies->begin();
	BodyContainer::iterator biEnd = bodies->end();
	for (; bi != biEnd; ++bi) {
		MaxId = math::max(MaxId, (*bi)->getId());
	}
	interactionsOnBody.resize(MaxId + 1);
	for (unsigned int i = 0; i < interactionsOnBody.size(); ++i) {
		interactionsOnBody[i].clear();
	}

	InteractionContainer::iterator ii    = scene->interactions->begin();
	InteractionContainer::iterator iiEnd = scene->interactions->end();
	for (; ii != iiEnd; ++ii) {
		if ((*ii)->isReal()) {
			if (static_cast<CapillaryPhysDelaunay*>((*ii)->phys.get())->meniscus) insert(*ii);
		}
	}

	return initialized = true;
}

bool BodiesMenisciiList1::insert(const shared_ptr<Interaction>& interaction)
{
	interactionsOnBody[interaction->getId1()].push_back(interaction);
	interactionsOnBody[interaction->getId2()].push_back(interaction);
	return true;
}


bool BodiesMenisciiList1::remove(const shared_ptr<Interaction>& interaction)
{
	interactionsOnBody[interaction->getId1()].remove(interaction);
	interactionsOnBody[interaction->getId2()].remove(interaction);
	return true;
}

std::list<shared_ptr<Interaction>>& BodiesMenisciiList1::operator[](int index) { return interactionsOnBody[index]; }

int BodiesMenisciiList1::size() { return interactionsOnBody.size(); }

void BodiesMenisciiList1::display()
{
	std::list<shared_ptr<Interaction>>::iterator firstMeniscus;
	std::list<shared_ptr<Interaction>>::iterator lastMeniscus;
	for (unsigned int i = 0; i < interactionsOnBody.size(); ++i) {
		if (!interactionsOnBody[i].empty()) {
			lastMeniscus = interactionsOnBody[i].end();
			for (firstMeniscus = interactionsOnBody[i].begin(); firstMeniscus != lastMeniscus; ++firstMeniscus) {
				if (*firstMeniscus) {
					if (firstMeniscus->get()) cerr << "(" << (*firstMeniscus)->getId1() << ", " << (*firstMeniscus)->getId2() << ") ";
					else
						cerr << "(void)";
				}
			}
			cerr << endl;
		} else
			cerr << "empty" << endl;
	}
}

BodiesMenisciiList1::BodiesMenisciiList1() { initialized = false; }

} // namespace yade

#endif // YADE_CGAL