-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulation.cpp
More file actions
1720 lines (1484 loc) · 55.4 KB
/
Copy pathSimulation.cpp
File metadata and controls
1720 lines (1484 loc) · 55.4 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
Simulation - Class encapsulating the simulation of the interactions of a
set of structural units, and user interactions upon those units.
Copyright (c) 2017-2025 Oliver Kreylos
The Nanotech Construction Kit is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The Nanotech Construction Kit is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with the Nanotech Construction Kit; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***********************************************************************/
#include "Simulation.h"
#include <string.h>
#include <utility>
#include <algorithm>
#include <stdexcept>
#include <Misc/SizedTypes.h>
#include <Misc/MessageLogger.h>
#include <Misc/OneTimeQueue.h>
#include <Misc/Marshaller.h>
#include <Misc/StandardValueCoders.h>
#include <Misc/ConfigurationFile.h>
#include <Misc/CompoundValueCoders.h>
#include <IO/File.h>
#include <Math/Math.h>
#include <Geometry/GeometryValueCoders.h>
#include "IO.h"
// DEBUGGING
#include <assert.h>
#include <iostream>
/*******************************************
Declaration of struct Simulation::UIRequest:
*******************************************/
struct Simulation::UIRequest
{
/* Embedded classes: */
public:
enum RequestType // Enumerated type for types of requests
{
PICK_POS,PICK_RAY,PASTE,CREATE,SET_STATE,COPY,DESTROY,RELEASE,SAVE_STATE,LOAD_STATE,NUM_REQUESTTYPES
};
/* Elements: */
RequestType requestType; // Type of this request
PickID pickId; // Pick ID associated with this request
Point pickPos; // Position at which to pick
Scalar pickRadius; // Radius for point pick requests
Vector pickDir; // Direction along which to pick
bool pickConnected; // Flag whether pick operations pick connected complexes
UnitTypeID createTypeId; // Type of unit to create
Point setPosition; // Position to set
Rotation setOrientation; // Orientation to set
Vector setLinearVelocity; // Linear velocity to set
Vector setAngularVelocity; // Angular velocity to set
IO::FilePtr file; // Pointer to the file from/to which to load/save state
Misc::Autopointer<SaveStateCompleteCallback> saveCompleteCallback; // Pointer to callback to call when a save operation is complete
SessionID loadSessionId; // Session ID associated with a load state request
/* Constructors and destructors: */
UIRequest(void) // Dummy constructor to avoid a ton of compiler warnings
:requestType(NUM_REQUESTTYPES),
pickId(0),
pickPos(Point::origin),pickRadius(0),pickDir(Vector::zero),pickConnected(false),
createTypeId(0),
setPosition(Point::origin),setLinearVelocity(Vector::zero),setAngularVelocity(Vector::zero),
loadSessionId(0)
{
}
};
/****************
Helper functions:
****************/
template <class ScalarParam>
ScalarParam increment(ScalarParam value); // Increments the given positive value to the next bigger representable value
template <>
Misc::Float32 increment(Misc::Float32 value)
{
/* Helper union: */
union
{
/* Elements: */
public:
Misc::Float32 f;
Misc::SInt32 i;
} incrementer;
/* Assign the value as float, increment as integer, and return as float: */
incrementer.f=value;
++incrementer.i;
return incrementer.f;
}
template <>
Misc::Float64 increment(Misc::Float64 value)
{
/* Helper union: */
union
{
/* Elements: */
public:
Misc::Float64 f;
Misc::SInt64 i;
} incrementer;
/* Assign the value as float, increment as integer, and return as float: */
incrementer.f=value;
++incrementer.i;
return incrementer.f;
}
/*********************************
Methods of class Simulation::Grid:
*********************************/
Simulation::Grid::Grid(void)
:cells(0),
unitCellIndexSize(0),unitCellIndices(0)
{
}
Simulation::Grid::~Grid(void)
{
delete[] cells;
delete[] unitCellIndices;
}
void Simulation::Grid::create(const Box& domain,const UnitTypeList& unitTypes,Scalar centralForceOvershoot,Scalar vertexForceRadius)
{
/* Calculate the minimum size of a grid cell based on the largest unit type, central force overshoot, and vertex force radius: */
Scalar minCellSize(0);
for(Misc::Vector<UnitType>::const_iterator utIt=unitTypes.begin();utIt!=unitTypes.end();++utIt)
{
/* Calculate the unit type's central force radius: */
Scalar centralForceRadius=utIt->radius*Scalar(2)+centralForceOvershoot;
if(minCellSize<centralForceRadius)
minCellSize=centralForceRadius;
/* Calculate the unit type's maximum vertex force radius: */
for(Misc::Vector<BondSite>::const_iterator bsIt=utIt->bondSites.begin();bsIt!=utIt->bondSites.end();++bsIt)
{
Scalar bondVertexForceRadius=Geometry::mag(bsIt->offset)*Scalar(2)+vertexForceRadius;
if(minCellSize<bondVertexForceRadius)
minCellSize=bondVertexForceRadius;
}
}
/* Calculate the size and layout of the acceleration grid: */
for(int i=0;i<3;++i)
{
/* Calculate the number of cells in this direction: */
numCells[i]=Size(Math::floor(domain.getSize(i)/minCellSize));
/* Calculate the grid cell size in this direction: */
cellSize[i]=domain.getSize(i)/Scalar(numCells[i]);
/* Slightly increase grid cell size until there is no chance of grid overshoot by rounding error: */
while(Index((domain.max[i]-domain.min[i])/cellSize[i])>=numCells[i])
cellSize[i]=increment(cellSize[i]);
/* Store the domain origin: */
origin[i]=domain.min[i];
}
// DEBUGGING
#if 0
std::cout<<"Grid size: "<<numCells[0]<<'x'<<numCells[1]<<'x'<<numCells[2]<<std::endl;
std::cout<<"Grid dell size: "<<cellSize[0]<<'x'<<cellSize[1]<<'x'<<cellSize[2]<<std::endl;
std::cout<<"Top indices: "<<int((domain.max[0]-origin[0])/cellSize[0])<<", "<<int((domain.max[1]-origin[1])/cellSize[1])<<", "<<int((domain.max[2]-origin[2])/cellSize[2])<<std::endl;
#endif
/* Allocate and initialize the acceleration grid: */
delete[] cells;
cells=new Cell[numCells[2]*numCells[1]*numCells[0]];
Cell* gcPtr=cells;
ptrdiff_t strides[3];
strides[0]=1;
for(int i=1;i<3;++i)
strides[i]=strides[i-1]*numCells[i-1];
ptrdiff_t offsets[6];
for(Index z=0;z<numCells[2];++z)
{
offsets[4]=z>0?-strides[2]:strides[2]*ptrdiff_t(numCells[2]-1);
offsets[5]=z<numCells[2]-1?strides[2]:-strides[2]*ptrdiff_t(numCells[2]-1);
for(Index y=0;y<numCells[1];++y)
{
offsets[2]=y>0?-strides[1]:strides[1]*ptrdiff_t(numCells[1]-1);
offsets[3]=y<numCells[1]-1?strides[1]:-strides[1]*ptrdiff_t(numCells[1]-1);
for(Index x=0;x<numCells[0];++x,++gcPtr)
{
offsets[0]=x>0?-strides[0]:strides[0]*ptrdiff_t(numCells[0]-1);
offsets[1]=x<numCells[0]-1?strides[0]:-strides[0]*ptrdiff_t(numCells[0]-1);
/* Store pointers to the grid cell's neighbors and itself: */
gcPtr->neighbors[0]=gcPtr+offsets[0]+offsets[2]+offsets[4];
gcPtr->neighbors[1]=gcPtr+offsets[2]+offsets[4];
gcPtr->neighbors[2]=gcPtr+offsets[1]+offsets[2]+offsets[4];
gcPtr->neighbors[3]=gcPtr+offsets[0]+offsets[4];
gcPtr->neighbors[4]=gcPtr+offsets[4];
gcPtr->neighbors[5]=gcPtr+offsets[1]+offsets[4];
gcPtr->neighbors[6]=gcPtr+offsets[0]+offsets[3]+offsets[4];
gcPtr->neighbors[7]=gcPtr+offsets[3]+offsets[4];
gcPtr->neighbors[8]=gcPtr+offsets[1]+offsets[3]+offsets[4];
gcPtr->neighbors[9]=gcPtr+offsets[0]+offsets[2];
gcPtr->neighbors[10]=gcPtr+offsets[2];
gcPtr->neighbors[11]=gcPtr+offsets[1]+offsets[2];
gcPtr->neighbors[12]=gcPtr+offsets[0];
gcPtr->neighbors[13]=gcPtr;
gcPtr->neighbors[14]=gcPtr+offsets[1];
gcPtr->neighbors[15]=gcPtr+offsets[0]+offsets[3];
gcPtr->neighbors[16]=gcPtr+offsets[3];
gcPtr->neighbors[17]=gcPtr+offsets[1]+offsets[3];
gcPtr->neighbors[18]=gcPtr+offsets[0]+offsets[2]+offsets[5];
gcPtr->neighbors[19]=gcPtr+offsets[2]+offsets[5];
gcPtr->neighbors[20]=gcPtr+offsets[1]+offsets[2]+offsets[5];
gcPtr->neighbors[21]=gcPtr+offsets[0]+offsets[5];
gcPtr->neighbors[22]=gcPtr+offsets[5];
gcPtr->neighbors[23]=gcPtr+offsets[1]+offsets[5];
gcPtr->neighbors[24]=gcPtr+offsets[0]+offsets[3]+offsets[5];
gcPtr->neighbors[25]=gcPtr+offsets[3]+offsets[5];
gcPtr->neighbors[26]=gcPtr+offsets[1]+offsets[3]+offsets[5];
}
}
}
/* Reset the unit cell index array: */
delete[] unitCellIndices;
unitCellIndexSize=0;
unitCellIndices=0;
}
void Simulation::Grid::reserve(Size numUnits)
{
/* Check if the unit cell index array is too small: */
if(unitCellIndexSize<numUnits)
{
/* Increase the size of the cell index array: */
Size newUnitCellIndexSize=unitCellIndexSize;
while(newUnitCellIndexSize<numUnits)
newUnitCellIndexSize=(newUnitCellIndexSize*5)/4+1;
/* Allocate a new array and copy over current indices: */
Index* newUnitCellIndices=new Index[newUnitCellIndexSize];
for(Index i=0;i<unitCellIndexSize;++i)
newUnitCellIndices[i]=unitCellIndices[i];
/* Replace the old array: */
delete[] unitCellIndices;
unitCellIndexSize=newUnitCellIndexSize;
unitCellIndices=newUnitCellIndices;
}
}
void Simulation::Grid::insertUnit(Index unitIndex,const UnitState& unit)
{
/* Find the grid cell containing the new unit: */
Index cellIndex=calcCellIndex(unit.position);
/* Add the unit to its grid cell's unit list: */
cells[cellIndex].unitIndices.push_back(unitIndex);
unitCellIndices[unitIndex]=cellIndex;
}
void Simulation::Grid::moveUnit(Index unitIndex,const UnitState& unit)
{
/* Find the new grid cell containing the given unit: */
Index cellIndex=calcCellIndex(unit.position);
/* Check if the unit changed grid cells: */
if(unitCellIndices[unitIndex]!=cellIndex)
{
/* Remove the unit from its previous grid cell's unit list: */
Cell& gc=cells[unitCellIndices[unitIndex]];
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
if(*uiIt==unitIndex)
{
/* Move the list's last entry to the front: */
*uiIt=gc.unitIndices.back();
/* Remove the copied last entry: */
gc.unitIndices.pop_back();
/* Stop searching: */
break;
}
/* Add the unit to its new grid cell's unit list: */
cells[cellIndex].unitIndices.push_back(unitIndex);
unitCellIndices[unitIndex]=cellIndex;
}
}
void Simulation::Grid::removeUnit(Index unitIndex)
{
/* Remove the removed unit from its grid cell's unit list: */
Cell& gc=cells[unitCellIndices[unitIndex]];
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
if(*uiIt==unitIndex)
{
/* Move the list's last entry to the current slot: */
*uiIt=gc.unitIndices.back();
/* Remove the copied last entry: */
gc.unitIndices.pop_back();
/* Stop searching: */
break;
}
}
void Simulation::Grid::changeUnitIndex(Index currentUnitIndex,Index newUnitIndex)
{
/* Move the unit's grid cell index to its new slot: */
unitCellIndices[newUnitIndex]=unitCellIndices[currentUnitIndex];
/* Change the index of the unit in its grid cell's unit list: */
Cell& gc=cells[unitCellIndices[newUnitIndex]];
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
if(*uiIt==currentUnitIndex)
{
/* Change the index to the new value: */
*uiIt=newUnitIndex;
/* Stop searching: */
break;
}
}
void Simulation::Grid::moveUnits(Size numUnits,const UnitState* unitStates)
{
const UnitState* uPtr=unitStates;
for(Index unitIndex=0;unitIndex<numUnits;++unitIndex,++uPtr)
{
/* Find the new grid cell containing the unit: */
Index cellIndex=calcCellIndex(uPtr->position);
/* Check if the unit changed grid cells: */
if(unitCellIndices[unitIndex]!=cellIndex)
{
/* Remove the unit from its previous grid cell's unit list: */
Cell& gc=cells[unitCellIndices[unitIndex]];
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
if(*uiIt==unitIndex)
{
/* Move the list's last entry to the front: */
*uiIt=gc.unitIndices.back();
/* Remove the copied last entry: */
gc.unitIndices.pop_back();
/* Stop searching: */
break;
}
/* Add the unit to its new grid cell's unit list: */
cells[cellIndex].unitIndices.push_back(unitIndex);
unitCellIndices[unitIndex]=cellIndex;
}
}
}
void Simulation::Grid::check(Size numUnits,const UnitState* unitStates) const
{
/* Check the grid for consistency: */
for(Index gci=0;gci<numCells[2]*numCells[1]*numCells[0];++gci)
{
Cell& gc=cells[gci];
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
assert(unitCellIndices[*uiIt]==gci);
}
for(Index ui=0;ui<numUnits;++ui)
{
Index gci=calcCellIndex(unitStates[ui].position);
assert(unitCellIndices[ui]==gci);
Cell& gc=cells[unitCellIndices[ui]];
Index numInstances=0;
for(std::vector<Index>::iterator uiIt=gc.unitIndices.begin();uiIt!=gc.unitIndices.end();++uiIt)
if(*uiIt==ui)
++numInstances;
assert(numInstances==1);
}
}
/***************************
Methods of class Simulation:
***************************/
Vector Simulation::wrapDistance(const Vector& distance) const
{
Vector result=distance;
for(int i=0;i<3;++i)
{
Scalar ds=domain.getSize(i);
if(result[i]>Math::div2(ds))
result[i]-=ds;
else if(result[i]<-Math::div2(ds))
result[i]+=ds;
}
return result;
}
Point Simulation::wrapPosition(const Point& position) const
{
Point result=position;
for(int i=0;i<3;++i)
{
/* Wrap the position along the current axis: */
Scalar ds=domain.getSize(i);
while(result[i]<domain.min[i])
result[i]+=ds;
while(result[i]>=domain.max[i])
result[i]-=ds;
}
return result;
}
PickID Simulation::getPickId(void)
{
/* Advance the pick ID until it is valid and unused: */
do
{
++lastPickId;
}
while(lastPickId==PickID(0)||pickRecords.isEntry(lastPickId));
/* Return the next pick ID: */
return lastPickId;
}
void Simulation::unpickUnit(PickID pickId,Index unitIndex)
{
/* Get the unit's current pick record list: */
PickRecordList& prl=pickRecords[pickId].getDest();
/* Remove the unit's record from the list: */
for(PickRecordList::iterator prlIt=prl.begin();prlIt!=prl.end();++prlIt)
if(prlIt->unitIndex==unitIndex)
{
/* Move the last pick record list entry to the front: */
*prlIt=prl.back();
prl.pop_back();
/* Stop searching: */
break;
}
}
void Simulation::pickUnits(UnitState* unitStates,Index unitIndex,const Point& pickPosition,const Rotation& pickOrientation,bool pickConnected,Simulation::PickRecordMap::Entry& pickRecord)
{
/* Check whether to pick connected units: */
if(pickConnected)
{
/* Create a queue of connected units and start with the given one: */
Misc::OneTimeQueue<Index> connectedUnits(17);
connectedUnits.push(unitIndex);
/* Follow connected bonds until the queue is empty: */
while(!connectedUnits.empty())
{
/* Pick and create a pick record entry for the first unit in the queue, if it is not picked already: */
PickRecord pr;
pr.unitIndex=connectedUnits.front();
connectedUnits.pop();
UnitState& u=unitStates[pr.unitIndex];
/* Unpick the unit if it is already part of another pick: */
if(u.pickId!=0)
unpickUnit(u.pickId,pr.unitIndex);
/* Pick the unit: */
u.pickId=pickRecord.getSource();
Rotation poInv=Geometry::invert(pickOrientation);
pr.positionOffset=poInv.transform(wrapDistance(u.position-pickPosition));
pr.orientationOffset=poInv*u.orientation;
pickRecord.getDest().push_back(pr);
/* Find all units bonded to the first one: */
const UnitType& ut=unitTypes[u.unitType];
for(Index bsi=0;bsi<ut.bondSites.size();++bsi)
{
Bond b(pr.unitIndex,bsi);
BondMap::Iterator bIt=bonds.findEntry(b);
if(!bIt.isFinished())
{
/* Put the unit at the other end of the bond into the queue: */
connectedUnits.push(bIt->getDest().unitIndex);
}
}
}
}
else
{
/* Create a pick record entry for the given unit: */
PickRecord pr;
pr.unitIndex=unitIndex;
UnitState& u=unitStates[unitIndex];
/* Unpick the unit if it is already part of another pick: */
if(u.pickId!=0)
unpickUnit(u.pickId,unitIndex);
/* Pick the unit: */
u.pickId=pickRecord.getSource();
Rotation poInv=Geometry::invert(pickOrientation);
pr.positionOffset=poInv.transform(wrapDistance(u.position-pickPosition));
pr.orientationOffset=poInv*u.orientation;
pickRecord.getDest().push_back(pr);
}
}
void Simulation::calcForces(Size numUnits,const UnitState* states,Vector* forces,Vector* torques) const
{
/* Zero out force arrays: */
for(Index i=0;i<numUnits;++i)
{
forces[i]=Vector::zero;
torques[i]=Vector::zero;
}
/* Retrieve dampening factors: */
Scalar ld=parameters.getLockedValue().linearDampening;
Scalar ad=parameters.getLockedValue().angularDampening;
/* Calculate central repelling forces between all pairs of units: */
for(Index ui0=0;ui0<numUnits;++ui0)
{
const UnitState& u0=states[ui0];
const UnitType& ut0=unitTypes[u0.unitType];
Scalar r0=ut0.radius;
/* Find all near-by units by searching neighbors of the unit's grid cell: */
const Grid::Cell& gc=grid.getCell(ui0);
for(int neighborIndex=0;neighborIndex<27;++neighborIndex)
{
const Grid::Cell* nPtr=gc.neighbors[neighborIndex];
for(std::vector<Index>::const_iterator ui1It=nPtr->unitIndices.begin();ui1It!=nPtr->unitIndices.end();++ui1It)
if(*ui1It>ui0)
{
const UnitState& u1=states[*ui1It];
const UnitType& ut1=unitTypes[u1.unitType];
Scalar r1=ut1.radius;
/* Calculate the wrapped distance vector between the units: */
Vector dist=wrapDistance(u1.position-u0.position);
Scalar distLen2=Geometry::sqr(dist);
/* Calculate the central repelling force between the two units: */
Scalar centralForceRadius=r0+r1+centralForceOvershoot;
Scalar centralForceRadius2=Math::sqr(centralForceRadius);
if(distLen2<centralForceRadius2)
{
Vector force=dist*(centralForceStrength*(Math::sqrt(distLen2)-centralForceRadius)/centralForceRadius2);
// DEBUGGING
// std::cout<<"Central interaction "<<ui0<<"<->"<<*ui1It<<" = "<<force<<std::endl;
forces[ui0]+=force;
forces[*ui1It]-=force;
}
}
}
}
/* Calculate attracting forces and torques from all bonds: */
for(BondMap::ConstIterator bIt=bonds.begin();!bIt.isFinished();++bIt)
{
/* Only process the "up-facing" subset of all bonds: */
if(bIt->getSource().unitIndex<bIt->getDest().unitIndex)
{
/* Retrieve the two bonded units: */
Index ui0=bIt->getSource().unitIndex;
const UnitState& u0=states[ui0];
const UnitType& ut0=unitTypes[u0.unitType];
Index bsi0=bIt->getSource().bondSiteIndex;
Index ui1=bIt->getDest().unitIndex;
const UnitState& u1=states[ui1];
const UnitType& ut1=unitTypes[u1.unitType];
Index bsi1=bIt->getDest().bondSiteIndex;
/* Calculate the wrapped distance vector between the units: */
Vector dist=wrapDistance(u1.position-u0.position);
/* Calculate the distance vector between the two bonding sites: */
Vector bs0=u0.orientation.transform(ut0.bondSites[bsi0].offset);
dist-=bs0;
Vector bs1=u1.orientation.transform(ut1.bondSites[bsi1].offset);
dist+=bs1;
/* Calculate the vertex attraction force: */
Scalar distLen2=Geometry::sqr(dist);
if(distLen2<=vertexForceRadius2)
{
/* Calculate an attractive force between the bond sites: */
Vector force=dist*(vertexForceStrength*(vertexForceRadius-Math::sqrt(distLen2))/vertexForceRadius2);
/* Calculate the linear velocity difference between the two bond sites: */
Vector dv=u1.linearVelocity;
dv+=u1.angularVelocity^bs1;
dv-=u0.linearVelocity;
dv-=u0.angularVelocity^bs0;
/* Calculate a dampening force between the bond sites: */
force+=dv*ld;
// DEBUGGING
// std::cout<<"Vertex interaction ("<<ui0<<", "<<bsi0<<")<->("<<ui1<<", "<<bsi1<<") = "<<force<<std::endl;
forces[ui0]+=force;
forces[ui1]-=force;
/* Calculate torques: */
torques[ui0]+=bs0^force;
torques[ui1]-=bs1^force;
/* Calculate the angular velocity difference along the unit's distance vector: */
Vector domega=u1.angularVelocity;
domega-=u0.angularVelocity;
Vector torque=domega*ad; // dist*((domega*dist)*ad/distLen2);
torques[ui0]+=torque;
torques[ui1]-=torque;
}
}
}
}
void Simulation::applyForces(Size numUnits,const UnitState* source,UnitState* dest,Vector* forces,Vector* torques,Scalar dt)
{
/* Process all units: */
Scalar att=Math::pow(parameters.getLockedValue().attenuation,dt);
const UnitState* sPtr=source;
UnitState* dPtr=dest;
for(Index ui=0;ui<numUnits;++ui,++sPtr,++dPtr)
{
/* Copy basic unit state: */
dPtr->unitType=sPtr->unitType;
const UnitType& ut=unitTypes[sPtr->unitType];
dPtr->pickId=sPtr->pickId;
/* Update linear and angular velocities unless the unit is locked by a pick record: */
dPtr->linearVelocity=sPtr->linearVelocity;
dPtr->angularVelocity=sPtr->angularVelocity;
if(sPtr->pickId==0)
{
Vector linearAcceleration=forces[ui];
linearAcceleration*=ut.invMass*dt;
dPtr->linearVelocity+=linearAcceleration;
Vector angularAcceleration=Vector(ut.invMomentOfInertia*torques[ui]);
angularAcceleration*=dt;
dPtr->angularVelocity+=angularAcceleration;
}
/* Update position and orientation: */
dPtr->position=wrapPosition(sPtr->position+dPtr->linearVelocity*dt);
dPtr->orientation=Rotation(dPtr->angularVelocity*dt)*sPtr->orientation;
dPtr->orientation.renormalize();
if(sPtr->pickId==0)
{
/* Attenuate velocities: */
dPtr->linearVelocity*=att;
dPtr->angularVelocity*=att;
}
}
/* Update the acceleration grid: */
grid.moveUnits(numUnits,dest);
}
void Simulation::updateBonds(Size numUnits,const UnitState* states)
{
/* Process all units: */
for(Index ui0=0;ui0<numUnits;++ui0)
{
const UnitState& u0=states[ui0];
const UnitType& ut0=unitTypes[u0.unitType];
// Scalar r0=ut0.radius; // Currently not used
/* Process all the unit's bond sites: */
for(Index bsi0=0;bsi0<ut0.bondSites.size();++bsi0)
{
/* Transform the bond site's offset to global coordinates: */
Vector bs0=u0.orientation.transform(ut0.bondSites[bsi0].offset);
/* Check if the bond site is already bonded: */
Bond b0(ui0,bsi0);
BondMap::Iterator bIt=bonds.findEntry(b0);
if(!bIt.isFinished())
{
/* Check if this is the "up" direction of the bond: */
if(bIt->getDest().unitIndex>ui0)
{
/* Check if the bond has become invalid: */
Index ui1=bIt->getDest().unitIndex;
const UnitState& u1=states[ui1];
const UnitType& ut1=unitTypes[u1.unitType];
Index bsi1=bIt->getDest().bondSiteIndex;
Vector bs1=u1.orientation.transform(ut1.bondSites[bsi1].offset);
/* Calculate the wrapped distance vector between the bond sites: */
Vector dist=wrapDistance(u1.position-u0.position);
dist-=bs0;
dist+=bs1;
if(Geometry::sqr(dist)>vertexForceRadius2)
{
/* Break the bond by removing both the "up" and "down" directions: */
// DEBUGGING
// std::cout<<"Breaking bond ("<<ui0<<", "<<bsi0<<")<->("<<ui1<<", "<<bsi1<<")"<<std::endl;
bonds.removeEntry(bIt);
bonds.removeEntry(Bond(ui1,bsi1));
}
}
}
else
{
/* Check if the bond site can bond with another near-by unit by searching neighbors of the unit's grid cell: */
const Grid::Cell& gc=grid.getCell(ui0);
for(int neighborIndex=0;neighborIndex<27;++neighborIndex)
{
const Grid::Cell* nPtr=gc.neighbors[neighborIndex];
for(std::vector<Index>::const_iterator ui1It=nPtr->unitIndices.begin();ui1It!=nPtr->unitIndices.end();++ui1It)
if(*ui1It>ui0)
{
const UnitState& u1=states[*ui1It];
const UnitType& ut1=unitTypes[u1.unitType];
Scalar r1=ut1.radius;
/* Calculate the wrapped distance vector between the units and offset it for the first bond site: */
Vector dist=wrapDistance(u1.position-u0.position);
dist-=bs0;
Scalar dLen2=Geometry::sqr(dist);
/* Check if the other unit is close enough to potentially bond: */
if(dLen2<=Math::sqr(r1+vertexForceRadius))
{
/* Check all bond sites on the other unit: */
for(Index bsi1=0;bsi1<ut1.bondSites.size();++bsi1)
{
/* Check that the other bond site is not already bonded: */
Bond b1(*ui1It,bsi1);
if(!bonds.isEntry(b1))
{
/* Calculate the bond site distance: */
Vector bDist=dist+u1.orientation.transform(ut1.bondSites[bsi1].offset);
if(Geometry::sqr(bDist)<=vertexForceRadius2)
{
/* Create a bond by inserting both the "up" and "down" halves into the bond map: */
// DEBUGGING
// std::cout<<"Creating bond ("<<ui0<<", "<<bsi0<<")<->("<<*ui1It<<", "<<bsi1<<")"<<std::endl;
bonds[b0]=b1;
bonds[b1]=b0;
/* Stop looking for bonding opportunities: */
goto doneCheckingBondSite;
}
}
}
}
}
}
doneCheckingBondSite:
; // Just to make compiler happy
}
}
}
}
void Simulation::save(UnitStateArray& states,IO::File& file) const
{
/* Write a file identifier: */
char tag[32];
memset(tag,0,sizeof(tag));
strcpy(tag,"NanotechConstructionKit 2.0\r\n");
file.write(tag,sizeof(tag));
/* Write the list of unit types: */
Misc::write(unitTypes,file);
/* Write the domain size: */
Misc::write(domain,file);
/* Write simulation parameters: */
file.write<Scalar>(vertexForceRadius);
file.write<Scalar>(vertexForceStrength);
file.write<Scalar>(centralForceOvershoot);
file.write<Scalar>(centralForceStrength);
/* Write the given unit state array: */
writeStateArray(states,file,false);
/* Write all bonds: */
file.write<Size>(bonds.getNumEntries()/2); // Only write "up" halves of bonds
for(BondMap::ConstIterator bIt=bonds.begin();!bIt.isFinished();++bIt)
{
/* Check if this is the "up" half of a bond: */
if(bIt->getSource().unitIndex<bIt->getDest().unitIndex)
{
file.write<Index>(bIt->getSource().unitIndex);
file.write<Index>(bIt->getSource().bondSiteIndex);
file.write<Index>(bIt->getDest().unitIndex);
file.write<Index>(bIt->getDest().bondSiteIndex);
}
}
}
void Simulation::load(IO::File& file,UnitStateArray& states)
{
/* Check the file identifier: */
char tag[32];
file.read(tag,sizeof(tag));
if(strcmp(tag,"NanotechConstructionKit 2.0\r\n")!=0)
throw std::runtime_error("Input file is not a unit file");
/* Read the list of unit types: */
Misc::read(file,unitTypes);
/* Read the domain size: */
Misc::read(file,domain);
/* Read simulation parameters: */
vertexForceRadius=file.read<Scalar>();
vertexForceRadius2=Math::sqr(vertexForceRadius);
vertexForceStrength=file.read<Scalar>();
centralForceOvershoot=file.read<Scalar>();
centralForceStrength=file.read<Scalar>();
/* Create the acceleration grid: */
grid.create(domain,unitTypes,centralForceOvershoot,vertexForceRadius);
/* Read units into the given unit state array: */
readStateArray(file,states,false);
/* Sort the read units into their appropriate grid cells: */
grid.reserve(states.states.size());
Index unitIndex=0;
for(UnitStateArray::UnitStateList::iterator sIt=states.states.begin();sIt!=states.states.end();++sIt,++unitIndex)
{
/* Add the unit to the acceleration grid: */
grid.insertUnit(unitIndex,*sIt);
}
/* Read bonds: */
Size numBonds=file.read<Size>();
bonds.clear();
for(Index i=0;i<numBonds;++i)
{
/* Read the bond: */
Bond b0;
b0.unitIndex=file.read<Index>();
b0.bondSiteIndex=file.read<Index>();
Bond b1;
b1.unitIndex=file.read<Index>();
b1.bondSiteIndex=file.read<Index>();
/* Insert the "up" and "down" halves of the bond into the bond map: */
bonds[b0]=b1;
bonds[b1]=b0;
}
// DEBUGGING
std::cout<<"Loaded file: "<<states.states.size()<<" units, "<<numBonds<<" bonds"<<std::endl;
}
Simulation::Simulation(const Misc::ConfigurationFileSection& configFileSection,const Box& sDomain)
:bonds(17),
forceArraySize(0),forces(0),torques(0),
loadSessionId(1),
lastPickId(0),pickRecords(17)
{
/* Read simulation parameters: */
vertexForceRadius=configFileSection.retrieveValue<Scalar>("./vertexForceRadius",vertexForceRadius);
vertexForceRadius2=Math::sqr(vertexForceRadius);
vertexForceStrength=configFileSection.retrieveValue<Scalar>("./vertexForceStrength",vertexForceStrength);
centralForceOvershoot=configFileSection.retrieveValue<Scalar>("./centralForceOvershoot",centralForceOvershoot);
centralForceStrength=configFileSection.retrieveValue<Scalar>("./centralForceStrength",centralForceStrength);
Parameters& p=parameters.startNewValue();
p.linearDampening=configFileSection.retrieveValue<Scalar>("./linearDampening",Scalar(0));
p.angularDampening=configFileSection.retrieveValue<Scalar>("./angularDampening",Scalar(0));
p.attenuation=configFileSection.retrieveValue<Scalar>("./attenuation",Scalar(0.9));
p.timeFactor=configFileSection.retrieveValue<Scalar>("./timeFactor",Scalar(10));
parameters.postNewValue();
mostRecentParameters=&p;
/* Read the list of unit types: */
std::vector<std::string> unitTypeNames=configFileSection.retrieveValue<std::vector<std::string> >("./structuralUnitTypes");
for(std::vector<std::string>::iterator utnIt=unitTypeNames.begin();utnIt!=unitTypeNames.end();++utnIt)
{
try
{
/* Go to the unit type's configuration section: */
Misc::ConfigurationFileSection utSec=configFileSection.getSection(utnIt->c_str());
/* Read a unit type definition: */
UnitType newUt;
newUt.name=utSec.retrieveString("./name",*utnIt);
newUt.radius=utSec.retrieveValue<Scalar>("./radius");
newUt.mass=utSec.retrieveValue<Scalar>("./mass");
newUt.invMass=Scalar(1)/newUt.mass;
newUt.momentOfInertia=utSec.retrieveValue<Tensor>("./momentOfInertia");
newUt.invMomentOfInertia=Geometry::invert(newUt.momentOfInertia);
newUt.bondSites=utSec.retrieveValue<Misc::Vector<BondSite> >("./bondSites");
newUt.meshVertices=utSec.retrieveValue<Misc::Vector<Point> >("./meshVertices");
newUt.meshTriangles=utSec.retrieveValue<Misc::Vector<Index> >("./meshTriangles");
/* Store the unit type: */
unitTypes.push_back(newUt);
}
catch(const std::runtime_error& err)
{
Misc::formattedUserError("Simulation::Simulation: Ignoring unit type %s due to exception %s",utnIt->c_str(),err.what());
}
}
/* Set the simulation domain: */
domain=sDomain;
/* Create the acceleration grid: */
grid.create(domain,unitTypes,centralForceOvershoot,vertexForceRadius);
/* Mark the session as valid: */
sessionId=loadSessionId;
/* Post an initial update to the unit states triple buffer: */
UnitStateArray& states=unitStates.startNewValue();
states.sessionId=sessionId;
states.timeStamp=1;
unitStates.postNewValue();
mostRecentStates=&states;
}
Simulation::Simulation(const Misc::ConfigurationFileSection& configFileSection,IO::File& file)
:bonds(17),
forceArraySize(0),forces(0),torques(0),
loadSessionId(0),
lastPickId(0),pickRecords(17)
{
/* Read simulation parameters: */
Parameters& p=parameters.startNewValue();
p.linearDampening=configFileSection.retrieveValue<Scalar>("./linearDampening",Scalar(0));
p.angularDampening=configFileSection.retrieveValue<Scalar>("./angularDampening",Scalar(0));
p.attenuation=configFileSection.retrieveValue<Scalar>("./attenuation",Scalar(0.9));
p.timeFactor=configFileSection.retrieveValue<Scalar>("./timeFactor",Scalar(10));
parameters.postNewValue();
mostRecentParameters=&p;
/* Post an initial update to the unit states triple buffer: */
UnitStateArray& states=unitStates.startNewValue();
states.sessionId=sessionId;
states.timeStamp=1;
unitStates.postNewValue();
mostRecentStates=&states;
/* Load the requested unit file in the back end: */
loadState(file);
}
Simulation::~Simulation(void)
{
delete[] forces;
delete[] torques;
}
bool Simulation::isSessionValid(void) const
{
return sessionId==loadSessionId;
}
const SimulationInterface::Parameters& Simulation::getParameters(void) const
{
return *mostRecentParameters;
}
void Simulation::setParameters(const SimulationInterface::Parameters& newParameters)
{
Parameters& p=parameters.startNewValue();
p=newParameters;
parameters.postNewValue();
mostRecentParameters=&p;
}
bool Simulation::lockNewState(void)
{