File size: 52,823 Bytes
24b81cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
//-----------------------------
// ENERGY MANAGER
//-----------------------------
/*
Author: Boris Vacula

Documentation can be found at DayZ Confluence >> Camping & Squatting >> Electricity >> Energy Manager functionalities

This system controls storage, spending and sharing of energy between instances.

Every EntityAI object which uses this API gains these functions:
	-It can store some amout of energy
	-It can use this amount of energy for any kind of functionality
	-It can share this energy with other devices plugged into it
	-It will have an ON/OFF switch
*/

class ComponentEnergyManager : Component
{
	protected const  float DEFAULT_UPDATE_INTERVAL = 15;
	protected static bool 			m_DebugPlugs = false; //true; // Use this to toggle visualisation of plug connections
	protected 		Shape			m_DebugPlugArrow;
	
	protected 		bool			m_IsSwichedOn;
	protected 		bool			m_IsSwichedOnPreviousState; // Necesarry due to synchronization of m_IsSwichedOn
	protected 		bool			m_IsPassiveDevice;
	protected 		bool			m_IsWorking;
	protected 		bool			m_CanWork;
	protected 		bool			m_CanStopWork;
	protected 		bool			m_RestorePlugState; // After server restart, this value reports if this device was plugged into something or not at the end of last session.
	protected 		bool			m_AutoSwitchOff;
	protected 		bool			m_ShowSocketsInInventory;
	protected 		bool			m_HasElectricityIcon; // Electricity icon over the item in inventory
	protected 		bool			m_AutoSwitchOffWhenInCargo;
	protected 		bool			m_IsPlugged; // Synchronized variable
	protected 		bool			m_ConvertEnergyToQuantity;
	
	protected 		int				m_MySocketID = -1;
	protected 		int				m_PlugType;
	protected 		int				m_EnergySourceStorageIDb1; // Storage persistence ID
	protected 		int				m_EnergySourceStorageIDb2; // Storage persistence ID
	protected 		int				m_EnergySourceStorageIDb3; // Storage persistence ID
	protected 		int				m_EnergySourceStorageIDb4; // Storage persistence ID
	protected 		int				m_AttachmentActionType;
	protected 		int				m_EnergySourceNetworkIDLow = -1;  // Network ID
	protected 		int				m_EnergySourceNetworkIDHigh = -1; // Network ID
	
	protected 		float			m_EnergyUsage;
	protected 		float			m_Energy;
	protected 		float			m_EnergyAtSpawn;
	protected 		float			m_EnergyStorageMax;
	protected 		float			m_ReduceMaxEnergyByDamageCoef;
	protected 		float			m_SocketsCount;
	protected 		float			m_CordLength;
	protected 		float			m_LastUpdateTime;
	protected 		float			m_WetnessExposure;
	protected 		float			m_UpdateInterval; // Interval of OnWork(...) calls and device updates.
	
	protected 		string			m_CordTextureFile;
	
	// Concatenated strings for p3d selections
	protected static const string	SOCKET_ 			= "socket_";
	protected static const string	_PLUGGED 			= "_plugged";
	protected static const string	_AVAILABLE 			= "_available";
	static const string				SEL_CORD_PLUGGED 	= "cord_plugged";
	static const string				SEL_CORD_FOLDED		= "cord_folded";
	
	protected ref TIntArray			m_CompatiblePlugTypes;
	EntityAI						m_EnergySource; // Energy source can be any EntityAI object
	ref array<EntityAI> 			m_PluggedDevices;
	ref map<string,EntityAI>		m_DeviceByPlugSelection;
	
	ref Timer 						m_UpdateTimer;
	ref Timer 						m_UpdateQuantityTimer;
	ref Timer 						m_DebugUpdate;
	
	const int MAX_SOCKETS_COUNT 	= 4;
	EntityAI m_Sockets[MAX_SOCKETS_COUNT];
	
	

	// Constructor
	void ComponentEnergyManager()
	{
		// Disable debug arrows on public release, so that they don't use their timers.
		#ifndef DEVELOPER
		m_DebugPlugs = false;
		#endif
	}
	
	void ~ComponentEnergyManager()
	{
		if (m_DebugPlugArrow)
		{
			m_DebugPlugArrow.Destroy();
			m_DebugPlugArrow = NULL; 
		}
	}

	// Initialization. Energy Manager is ready.
	override void Event_OnInit()
	{
		m_ThisEntityAI.m_EM = this;
		GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnInitEnergy", NULL, 0);
	}
	
	// Update debug arrows
	void DebugUpdate()
	{
		if ( GetDebugPlugs() )
		{
			if ( GetGame().IsMultiplayer()  &&  GetGame().IsServer() )
			{
				if (m_DebugUpdate)
					m_DebugUpdate.Stop();
				
				return;
			}
		
			if (m_DebugPlugArrow)
			{
				m_DebugPlugArrow.Destroy();
				m_DebugPlugArrow = NULL; 
			}
			
			if ( GetEnergySource() )
			{
				vector from = GetEnergySource().GetPosition() + "0 0.1 0";
				vector to = m_ThisEntityAI.GetPosition() + "0 0.1 0";
				
				//No need to draw an arrow in this situation as it would not be visible
				if ( vector.DistanceSq(from, to) == 0 )
					return;
				
				if ( m_ThisEntityAI.GetType() == "BarbedWire" ) // Special case for debugging of electric fences. Temporal code until offsets in fences are fixed.
				{
					EntityAI BBB = m_ThisEntityAI.GetHierarchyParent();
					
					if ( BBB  &&  BBB.GetType() == "Fence" )
					{
						to = to + "0 -1.3 0";
					}
				}
				
				m_DebugPlugArrow = DrawArrow( from, to );
			}
		}
	}
	
	Shape DrawArrow(vector from, vector to, float size = 0.5, int color = 0xFFFFFFFF, float flags = 0)
	{
		vector dir = to - from;
		dir.Normalize();
		vector dir1 = dir * size;
		size = size * 0.5;
	
		vector dir2 = dir.Perpend() * size;
	
		vector pts[5];
		pts[0] = from;
		pts[1] = to;
		pts[2] = to - dir1 - dir2;
		pts[3] = to - dir1 + dir2;
		pts[4] = to;
		
		return Shape.CreateLines(color, flags, pts, 5);
	}

	EntityAI GetThisEntityAI()
	{
		return m_ThisEntityAI;
	}
	
	// Prepare everything
	override void Event_OnAwake()
	{
		string cfg_item = "CfgVehicles " + m_ThisEntityAI.GetType();
		string cfg_energy_manager = cfg_item + " EnergyManager ";
		
		// Read all config parameters
		m_EnergyUsage					= GetGame().ConfigGetFloat(cfg_energy_manager + "energyUsagePerSecond");
		bool switch_on					= GetGame().ConfigGetFloat(cfg_energy_manager + "switchOnAtSpawn");
		m_AutoSwitchOff					= GetGame().ConfigGetFloat(cfg_energy_manager + "autoSwitchOff");
		m_HasElectricityIcon			= GetGame().ConfigGetFloat(cfg_energy_manager + "hasIcon");
		m_AutoSwitchOffWhenInCargo 		= GetGame().ConfigGetFloat(cfg_energy_manager + "autoSwitchOffWhenInCargo");
		
		m_EnergyAtSpawn					= GetGame().ConfigGetFloat(cfg_energy_manager + "energyAtSpawn");
		m_Energy = m_EnergyAtSpawn;
		m_EnergyStorageMax				= GetGame().ConfigGetFloat(cfg_energy_manager + "energyStorageMax");
		m_ReduceMaxEnergyByDamageCoef	= GetGame().ConfigGetFloat(cfg_energy_manager + "reduceMaxEnergyByDamageCoef");
		m_SocketsCount					= GetGame().ConfigGetFloat(cfg_energy_manager + "powerSocketsCount");
		
		m_IsPassiveDevice				= GetGame().ConfigGetFloat(cfg_energy_manager + "isPassiveDevice");
		m_CordLength 					= GetGame().ConfigGetFloat(cfg_energy_manager + "cordLength");
		m_PlugType 						= GetGame().ConfigGetFloat(cfg_energy_manager + "plugType");
		
		m_AttachmentActionType			= GetGame().ConfigGetFloat(cfg_energy_manager + "attachmentAction");
		m_WetnessExposure				= GetGame().ConfigGetFloat(cfg_energy_manager + "wetnessExposure");
		
		float update_interval			= GetGame().ConfigGetFloat(cfg_energy_manager + "updateInterval");
		
		m_ConvertEnergyToQuantity		= GetGame().ConfigGetFloat(cfg_energy_manager + "convertEnergyToQuantity");
		
		
		// Check if energy->quantity converion is configured properly
		float cfg_max_quantity = GetGame().ConfigGetFloat (cfg_item + " varQuantityMax");
		
		if (m_ConvertEnergyToQuantity  &&  cfg_max_quantity <= 0)
		{
			string error = "Error! Item " + m_ThisEntityAI.GetType() + " has invalid configuration of the energy->quantity conversion feature. To fix this, add 'varQuantityMax' parameter with value higher than 0 to the item's config. Then make sure to re-build the PBO containing this item!";
			Error(error);
			m_ConvertEnergyToQuantity = false;
		}
		else
		{
			if (m_ConvertEnergyToQuantity)
			{
				if (!m_UpdateQuantityTimer)
					m_UpdateQuantityTimer = new Timer( CALL_CATEGORY_SYSTEM );
				
				m_UpdateQuantityTimer.Run( 0.3 , this, "OnEnergyAdded", NULL, false);
			}
		}
		
		// Set update interval
		if ( update_interval <= 0 )
			update_interval = DEFAULT_UPDATE_INTERVAL;
		
		SetUpdateInterval( update_interval );
		
		// If energyAtSpawn is present, then use its value for energyStorageMax if that cfg param is not present (for convenience's sake)
		string cfg_check_energy_limit = cfg_energy_manager + "energyStorageMax";
		
		if ( !GetGame().ConfigIsExisting (cfg_check_energy_limit)  &&  m_Energy > 0 )
		{
			m_EnergyStorageMax = m_Energy;
		}
		
		// Fill m_CompatiblePlugTypes
		string cfg_check_plug_types = cfg_energy_manager + "compatiblePlugTypes";
		
		if ( GetGame().ConfigIsExisting (cfg_check_plug_types) )
		{
			m_CompatiblePlugTypes = new TIntArray;
			GetGame().ConfigGetIntArray(cfg_check_plug_types, m_CompatiblePlugTypes);	
		}
		
		if (GetSocketsCount() > 0)
			m_PluggedDevices = new array<EntityAI>;
		
		if ( m_CordLength < 0 )
		{
			m_CordLength = 0;
			string error_message_cord = "Warning! " + m_ThisEntityAI.GetType() + ": config parameter 'cordLength' is less than 0! Cord length should not be negative!";
			DPrint(error_message_cord);
		}
		
		if (GetSocketsCount() > 0)
		{
			m_DeviceByPlugSelection = new map<string,EntityAI>;
			// Prepare the m_DeviceByPlugSelection
			string cfg_animation_sources = "cfgVehicles " + m_ThisEntityAI.GetType() + " " + "AnimationSources ";
			int animation_sources_count = GetGame().ConfigGetChildrenCount(cfg_animation_sources);
			
			for (int i_selection = 0; i_selection < animation_sources_count; i_selection++)
			{
				// TO DO: This could be optimized so not all selections on item are considered as plug/socket selections.
				string selection;
				GetGame().ConfigGetChildName(cfg_animation_sources, i_selection, selection);
				m_DeviceByPlugSelection.Set(selection, NULL);
			}
		}
		
		
		
		// Prepare sockets
		if ( m_SocketsCount > MAX_SOCKETS_COUNT )
		{
			m_SocketsCount = MAX_SOCKETS_COUNT;
			string error_message_sockets = "Error! " + m_ThisEntityAI.GetType() + ": config parameter 'powerSocketsCount' is higher than the current limit (" + MAX_SOCKETS_COUNT.ToString() + ")! Raise the limit (constant MAX_SOCKETS_COUNT) or decrease the powerSocketsCount parameter for this device!";
			DPrint(error_message_sockets);
		}
		
		m_Sockets[MAX_SOCKETS_COUNT]; // Handles selections for plugs in the sockets. Feel free to change the limit if needed.
		
		GetGame().ConfigGetText(cfg_energy_manager + "cordTextureFile", m_CordTextureFile); 
		
		if ( switch_on )
		{
			SwitchOn();
		}
		
		for ( int i = 0; i <= GetSocketsCount(); ++i )
		{
			m_ThisEntityAI.HideSelection ( SOCKET_ + i.ToString() + _PLUGGED );
		}
		
		// Show/hide inventory sockets
		m_ShowSocketsInInventory = false;
		if ( GetSocketsCount() > 0  &&  IsPlugCompatible(PLUG_COMMON_APPLIANCE)  &&  m_ThisEntityAI.GetType() != "MetalWire" ) // metal wire filter is hopefully temporal.
		{
			m_ShowSocketsInInventory = true;
		}
		
		m_CanWork = HasEnoughStoredEnergy();
		
		m_ThisEntityAI.HideSelection( SEL_CORD_PLUGGED );
		
		
		#ifdef DIAG_DEVELOPER
		GetGame().m_EnergyManagerArray.Insert( this );
		#endif
	}

	// Returns the type of this component
	override int GetCompType()
	{
		return COMP_TYPE_ENERGY_MANAGER;
	}
	
	// When the object is deleted
	void OnDeviceDestroyed()
	{
		bool was_working = m_ThisEntityAI.GetCompEM().IsWorking();
		
		SwitchOff();
		UnplugAllDevices();
		UnplugThis();
		SetPowered( false );
		
		if ( was_working )
			m_ThisEntityAI.OnWorkStop();
		;
	}
	
	//Restart the debug timer when relogging
	void RefreshDebug()
	{
		if ( m_DebugPlugs )
		{
			if ( !m_DebugUpdate )
				m_DebugUpdate = new Timer( CALL_CATEGORY_SYSTEM );
			
			if ( !m_DebugUpdate.IsRunning() )
				m_DebugUpdate.Run(0.01, this, "DebugUpdate", NULL, true);
		}
		else
		{
			if ( m_DebugPlugArrow )
			{
				m_DebugPlugArrow.Destroy();
				m_DebugPlugArrow = NULL; 
			}
		}
	}
	
	bool GetDebugPlugs()
	{
		return m_DebugPlugs;
	}
	
	void SetDebugPlugs( bool newVal )
	{
		m_DebugPlugs = newVal;
		RefreshDebug();
	}

	//======================================================================================
	// 									 PUBLIC FUNCTIONS
	// 						Use these to control the Energy Manager
	// Functions are in order of their return value: void, bool, int, float, string, array.
	//======================================================================================

	//! Energy manager: Switches ON the device so it starts doing its work if it has enough energy.
	void SwitchOn()
	{
		m_IsSwichedOnPreviousState = m_IsSwichedOn;
		
		if (GetGame().IsServer() || !GetGame().IsMultiplayer())
		{
			if ( CanSwitchOn() )
			{
				m_IsSwichedOn = true;
				Synch();
				
				DeviceUpdate(); // 'Wake up' this device now
				StartUpdates();
				
				// 'Wakes up' all connected devices
				WakeUpWholeBranch( m_ThisEntityAI );
				
				UpdateCanWork();
				
				// Call event
				GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnSwitchOn", NULL, 0);
			}
		}
		
		if ( !GetGame().IsServer()  &&  GetGame().IsMultiplayer()/*  &&  CanSwitchOn() */) // I want the CanSwitchOn() check, but when it's here, the OnSwitchOn() event is never called on client-side due to engine's synchronization system changing the m_IsSwichedOn to true without any specific event beign called. (Yes there is OnVariablesSynchronized() but that is called also when m_CanWork is synchronized, so I need to write a method of knowing when was this specific value changed.)
		{
			GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnSwitchOn", NULL, 0);
		}
	}

	//! Energy manager: Switches OFF the device.
	void SwitchOff()
	{
		m_IsSwichedOnPreviousState = m_IsSwichedOn;
		
		if (GetGame().IsServer() || !GetGame().IsMultiplayer())
		{
			if ( CanSwitchOff() )
			{
				m_IsSwichedOn = false;
				Synch();
				
				if ( IsWorking() )
				{
					StopUpdates();
					DeviceUpdate();
				}
				
				// 'Wakes up' all connected devices
				WakeUpWholeBranch( m_ThisEntityAI );

				UpdateCanWork();
								
				// Call event
				GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnSwitchOff", NULL, 0);
			}
		}
		
		if ( !GetGame().IsServer()  &&  GetGame().IsMultiplayer() )
		{
			m_IsSwichedOn = false;
			GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnSwitchOff", NULL, 0);
		}
	}

	//! Energy manager: Changes the status of this device. When it's passive (true), the main timer and OnWork events are not used.
	void SetPassiveState(bool state = true)
	{
		m_IsPassiveDevice = state;
		if ( !m_IsPassiveDevice )
		{
			DeviceUpdate();
		}
	}

	//! Energy manager: Unplugs the given device from this one.
	void UnplugDevice(EntityAI device_to_unplug)
	{
		if ( GetGame() )
		{
			int indexStart	= GetPluggedDevicesCount() - 1;
			bool deviceFound = false;
			
			for (int i = indexStart; i >= 0; --i)
			{
				EntityAI plugged_device = GetPluggedDevices().Get(i);
				
				if (plugged_device == device_to_unplug)
				{
					GetPluggedDevices().Remove(i);
					deviceFound = true;
					break;
				}
			}
			
			if (deviceFound)
			{
				int socket_ID = device_to_unplug.GetCompEM().GetMySocketID();
				UnplugCordFromSocket(socket_ID);
				device_to_unplug.GetCompEM().SetEnergySource(null);
				device_to_unplug.GetCompEM().DeviceUpdate();
				device_to_unplug.GetCompEM().StartUpdates();
				device_to_unplug.GetCompEM().WakeUpWholeBranch(m_ThisEntityAI);
				
				if (m_DebugPlugs && m_DebugPlugArrow)
				{
					m_DebugPlugArrow.Destroy();
					m_DebugPlugArrow = null;
				}
				
				OnOwnSocketReleased(device_to_unplug);
				device_to_unplug.GetCompEM().OnIsUnplugged(m_ThisEntityAI);
				device_to_unplug.ShowSelection(SEL_CORD_FOLDED);
				device_to_unplug.HideSelection(SEL_CORD_PLUGGED);
			}
		}
	}

	//! Energy manager: Unplugs this device from its power source
	void UnplugThis()
	{
		if (GetGame())
		{
			if (GetEnergySource())
			{
				GetEnergySource().GetCompEM().UnplugDevice(m_ThisEntityAI);
			}
		}
	}
	
	//! Energy manager: Unplugs everything directly connected to this device
	void UnplugAllDevices()
	{
		if ( GetPluggedDevices() ) // This check is necesarry in case this function is called before initialization
		{
			int indexStart	= GetPluggedDevicesCount() - 1;
			for (int i = indexStart; i >= 0; --i)
			{
				UnplugDevice(GetPluggedDevices().Get(i));
			}
		}
	}
	
	// Used only for storing of the plug's state through server restart
	void RestorePlugState(bool state)
	{
		m_RestorePlugState = state;
	}

	//! Energy manager: Sets stored energy for this device. It ignores the min/max limit!
	void SetEnergy(float new_energy)
	{
		if (GetGame().IsServer() || !GetGame().IsMultiplayer()) // Client can't change energy value.
		{
			m_ThisEntityAI.SetWeightDirty();
			float old_energy = m_Energy;
			m_Energy = new_energy;
			
			if ( old_energy - GetEnergyUsage() <= 0 || (old_energy != new_energy && Math.Min(old_energy,new_energy) <= 0) )
			{
				UpdateCanWork();
			}
		}
	}
	
	//! Energy manager: Sets stored energy for this device between 0 and MAX based on relative input value between 0 and 1
	void SetEnergy0To1(float energy01)
	{
		SetEnergy( Math.Lerp(0, GetEnergyMax(),energy01));
	}

	//! Energy manager: Shows/Hides all selections this system works with. Call this if something is wrong with selections (like during Init and Restore event in config)
	void UpdateSelections()
	{
		// Lets update sockets, if there are any
		int slots_c = GetSocketsCount();
		
		for ( int i = 0; i < slots_c; ++i )
		{
			EntityAI plug_owner = GetDeviceBySocketID(i);
			
			if ( plug_owner )
			{
				string plugged_selection = SOCKET_ + (i+1).ToString() + _PLUGGED;
				string available_selection = SOCKET_ + (i+1).ToString() + _AVAILABLE;
				m_ThisEntityAI.ShowSelection ( plugged_selection );
				m_ThisEntityAI.HideSelection ( available_selection );
				string texture_path = plug_owner.GetCompEM().GetCordTextureFile();
				int selection_index = m_ThisEntityAI.GetHiddenSelectionIndex( plugged_selection );
				m_ThisEntityAI.SetObjectTexture(selection_index, texture_path );
			}
			else
			{
				m_ThisEntityAI.ShowSelection ( SOCKET_ + (i+1).ToString() + _AVAILABLE );
				m_ThisEntityAI.HideSelection ( SOCKET_ + (i+1).ToString() + _PLUGGED );
			}
		}
		
		// Now lets update the cord/plug state
		if ( GetEnergySource() )
		{
			m_ThisEntityAI.ShowSelection ( SEL_CORD_PLUGGED );
			m_ThisEntityAI.HideSelection ( SEL_CORD_FOLDED );
		}
		else
		{
			m_ThisEntityAI.ShowSelection ( SEL_CORD_FOLDED );
			m_ThisEntityAI.HideSelection ( SEL_CORD_PLUGGED );
		}
	}

	//! Energy manager: Unplugs this device when it's necesarry
	void UpdatePlugState()
	{
		if (m_ThisEntityAI.GetCompEM().GetEnergySource())
		{
			EntityAI player = m_ThisEntityAI.GetHierarchyRootPlayer();
			// Check if the item is held in hands during advanced placement
			if (player)
			{
				// Measure distance from the player
				vector playerPosition = player.GetPosition();
				if (!IsEnergySourceAtReach(playerPosition, 5))
					UnplugThis();
			}
			else
			{
				// Measure distance from the device
				vector itemPosition = m_ThisEntityAI.GetPosition();
				
				if (m_ThisEntityAI.GetHierarchyParent())
					itemPosition = m_ThisEntityAI.GetHierarchyParent().GetPosition();
				
				if (!IsEnergySourceAtReach(itemPosition))
					UnplugThis();
			}
		}
	}

	// Returns an array of plug types this device can accept
	void GetCompatiblePlugTypes(out TIntArray IDs)
	{
		IDs = m_CompatiblePlugTypes;
	}

	// Stores IDs of the energy source.
	void StoreEnergySourceIDs(int b1, int b2, int b3, int b4)
	{
		m_EnergySourceStorageIDb1 = b1;
		m_EnergySourceStorageIDb2 = b2;
		m_EnergySourceStorageIDb3 = b3;
		m_EnergySourceStorageIDb4 = b4;
	}
	
	//! Energy manager: Changes the maximum amount of energy this device can store (when pristine).
	void SetEnergyMaxPristine(float new_limit)
	{
		m_EnergyStorageMax = new_limit;
	}
	
	//! Energy manager: Changes the length of the virtual power cord.
	void SetCordLength( float new_length )
	{
		m_CordLength = new_length;
	}
	
	// Sets the plug type (for plug -> socket compatibility checks).
	void SetPlugType( int new_type )
	{
		m_PlugType = new_type;
	}
	
	// Sets the new attachment action type.
	void SetAttachmentAction( int new_action_type )
	{
		m_AttachmentActionType = new_action_type;
	}
	
	//! Energy manager: Changes the energy usage per second.
	void SetEnergyUsage( float new_usage )
	{
		m_EnergyUsage = new_usage;
	}
	
	//! Energy manager: Resets energy usage to default (config) value.
	void ResetEnergyUsage()
	{
		string cfg_energy_usage = "CfgVehicles " + m_ThisEntityAI.GetType() + " EnergyManager ";
		m_EnergyUsage = GetGame().ConfigGetFloat (cfg_energy_usage + "energyUsagePerSecond");
	}
	
	// Sets path to the cord texture file.
	void SetCordTextureFile( string new_path )
	{
		m_CordTextureFile = new_path;
	}
	
	// Sets energy source. Intended to be called only on client through RPC.
	void SetEnergySourceClient( EntityAI source )
	{	
		SetEnergySource(source);
	}
	
	//! Energy manager: Stores the device which is plugged into the given socket ID.
	void SetDeviceBySocketID(int id, EntityAI plugged_device)
	{
		m_Sockets[id] = plugged_device;
	}
	
		
	//! Energy manager: Sets visibility of the electricity icon (bolt).
	void SetElectricityIconVisibility( bool make_visible )
	{
		m_HasElectricityIcon = make_visible;
	}
	
	// Checks whenever this device can work or not and updates this information on all clients. Can be called many times per frame because synchronization happens only once if a change has occured.
	void UpdateCanWork()
	{
		if (GetGame().IsServer() || !GetGame().IsMultiplayer())
		{
			bool current_state = CanWork();
			
			if (current_state != m_CanWork)
			{
				m_CanWork = current_state;
				Synch();
				
				if ( m_ThisEntityAI && m_ThisEntityAI.GetHierarchyParent() && m_ThisEntityAI.GetHierarchyParent().GetCompEM() )
				{
					m_ThisEntityAI.GetHierarchyParent().GetCompEM().UpdateCanWork();
				}
			}
		}
	}
	
	void HandleMoveInsideCargo(EntityAI container)
	{
		if ( m_AutoSwitchOffWhenInCargo )
		{
			if (IsSwitchedOn())
			{
				SwitchOff();
			}
		}
	}
	
	//! Energy manager: Sets the interval of the OnWork(...) calls. Changing this value does not change the rate of energy consumption.
	void SetUpdateInterval( float value )
	{
		m_UpdateInterval = value;
	}
	
	// Returns true if this device was plugged into something at the end of previous session
	bool GetRestorePlugState()
	{
		return m_RestorePlugState;
	}
	
	//! Energy manager: Attempts to plug this device into the energy_source. Returns true if the action was successfull, or false if not (due to plug incompatibility or no free socket on the receiver). The ID of the power socket is chosen automatically unless optional parameter socket_id is used (starting from 0). If the given ID is not free then a free socket is found.
	bool PlugThisInto(EntityAI energy_source, int socket_id = -1)
	{
		return energy_source.GetCompEM().PlugInDevice(m_ThisEntityAI, socket_id);
	}
	
	//! Energy manager: Checks if the device can be switched ON
	bool CanSwitchOn()
	{
		if ( !IsSwitchedOn() )
		{
			return true;
		}
		
		return false;
	}

	
	/**
	\brief Energy manager: Checks whenever this device can do work or not.
		\param test_energy \p float optional parameter will overwite the default energy consumption value of this device.
		\return \p bool Returns true if this device will work when it's switched on. Otherwise it returns false.
	*/
	bool CanWork( float test_energy = -1)
	{
		if ( GetGame().IsMultiplayer()  &&  GetGame().IsClient() )
		{
			return m_CanWork;
		}
		
		if (m_ThisEntityAI && m_ThisEntityAI.IsRuined())
		{
			return false;
		}
		
		// Check if the power source(s) (which can be serially connected) can provide needed energy.
		float 		energy_usage 	= test_energy;
		float 		gathered_energy = GetEnergy();
		EntityAI	energy_source 	= GetEnergySource();
		
		if (energy_usage == -1)
		{
			energy_usage = GetEnergyUsage();
		}
		
		if ( !CheckWetness() )
		{
			return false;
		}
		
		if (gathered_energy <= 0 && energy_usage <= 0) //empty power source
		{
			return false;
		}
		
		int cycle_limit = 500; // Sanity check to definitely avoid infinite cycles
		
		while ( gathered_energy < energy_usage ) // Look for energy source if we don't have enough stored energy
		{
			// Safetycheck!
			if (cycle_limit > 0)
			{
				cycle_limit--;
			}
			else
			{
				DPrint("Energy Manager ERROR: The 'cycle_limit' safety break had to be activated to prevent possible game freeze. Dumping debug information...");
				//Print(m_ThisEntityAI);
				//Print(this);
				//Print(energy_source);
				
				if (energy_source.GetCompEM())
				{
					//Print(energy_source.GetCompEM());
				}
				
				//Print(gathered_energy);
				//Print(energy_usage);
				
				//Print(m_ThisEntityAI.GetPosition());
				
				if (energy_source)
				{
					//Print(energy_source.GetPosition());
				}
				
				//Print("End of the 'cycle_limit' safety break ^ ");
				
				return false;
			}
			// ^ Safetycheck!
			
			if ( energy_source  &&  energy_source != m_ThisEntityAI  &&  !energy_source.IsRuined()  &&  energy_source.GetCompEM()  &&  energy_source.GetCompEM().IsSwitchedOn()  &&  energy_source.GetCompEM().CheckWetness() )
			{
				gathered_energy = gathered_energy + energy_source.GetCompEM().GetEnergy();
				energy_source = energy_source.GetCompEM().GetEnergySource();
			}
			else
			{
				// No power source, no energy.
				return false;
			}
		}
		
		// Enough energy was found
		return true;
	}

	//! Energy manager: Checks if this device is being stopped from working by its wetness level. Returns true when its wetness is not blocking it, false when its to owet to work.
	bool CheckWetness()
	{
		return (m_ThisEntityAI.GetWet() <= 1-m_WetnessExposure);
	}
	
	//! Energy manager: Checks if the device can be switched OFF
	bool CanSwitchOff()
	{
		if ( IsPassive() )
		{
			return false;
		}
		
		return IsSwitchedOn();
	}

	// Returns previous state of the switch.
	bool GetPreviousSwitchState()
	{
		return m_IsSwichedOnPreviousState;
	}
	
	//! Energy manager: Returns state of the switch. Whenever the device is working or not does not matter. Use IsWorking() to account for that as well.
	bool IsSwitchedOn()
	{
		return m_IsSwichedOn;
	}

	//! Energy manager: Returns true if the cord of this device is folded. Returns false if it's plugged.
	bool IsCordFolded()
	{
		if ( IsPlugged() )
			return false;
		
		return true;
	}
	
	//! Energy manager: Returns true if this device is set to be passive. False if otherwise.
	bool IsPassive()
	{
		return m_IsPassiveDevice;
	}

	//! Energy manager: Returns true if this device is plugged into some other device (even if they are OFF or ruined). Otherwise it returns false.
	bool IsPlugged()
	{
		return m_IsPlugged;
	}
	
	
	//! Energy manager: Consumes the given amount of energy. If there is not enough of stored energy in this device, then it tries to take it from its power source, if any exists. Returns true if the requested amount of energy was consumed. Otherwise it returns false.
	bool ConsumeEnergy(float amount)
	{
		return FindAndConsumeEnergy(m_ThisEntityAI, amount, true);
	}

	//! Energy manager: Returns true if this device is working right now.
	bool IsWorking()
	{
		return m_IsWorking;
	}

	//! Energy manager: Returns true if this device has enough of stored energy for its own use.
	bool HasEnoughStoredEnergy()
	{
		if ( GetEnergy() > GetEnergyUsage() )
		{
			return true;
		}
		
		return false;
	}

	//! Energy manager: Returns true if this device has any free socket to receive a plug. If optional parameter socket_id is provided then only that socket ID is checked.
	bool HasFreeSocket( int socket_id = -1 )
	{
		if (socket_id == -1)
		{
			int plugged_devices = GetPluggedDevicesCount();
			int plugged_devices_limit = GetSocketsCount();
			
			if ( plugged_devices < plugged_devices_limit )
			{
				return true;
			}
			
			return false;
		}
		else
		{
			EntityAI device = GetDeviceBySocketID(socket_id);
			
			if (device)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
	}

	//! Energy manager: Checks if the given plug is compatible with this device's socket. Used by CanReceivePlugFrom() method.
	bool IsPlugCompatible(int plug_ID)
	{
		if ( plug_ID == PLUG_UNDEFINED )
		{
			return true; // When plugType is undefined in config then make it compatible.
		}
		
		if ( m_CompatiblePlugTypes )
		{
			for ( int i = 0; i < m_CompatiblePlugTypes.Count(); i++ )
			{
				int plug_ID_to_Check = m_CompatiblePlugTypes.Get(i);
				
				if ( plug_ID_to_Check == plug_ID )
				{
					return true;
				}
			}
		}
		else
		{
			// Since the config parameter compatiblePlugTypes is not present, then accept all plugs for simplicity's sake
			return true;
		}
		
		return false;
	}
	
	//! Energy manager: Returns true if this device can receive power plug of the other device.
	bool CanReceivePlugFrom( EntityAI device_to_plug )
	{
		// The following conditions are broken down for the sake of easier reading/debugging.
		
		if ( HasFreeSocket()  &&  device_to_plug != m_ThisEntityAI)
		{
			if ( device_to_plug.GetCompEM().GetEnergySource() != m_ThisEntityAI)
			{	
				if ( IsPlugCompatible(device_to_plug.GetCompEM().GetPlugType()) )
				{
					if ( device_to_plug.GetCompEM().IsEnergySourceAtReach( device_to_plug.GetPosition(), 0, m_ThisEntityAI.GetPosition() ) )
					{
						return true;
					}
				}
			}
		}
		
		return false;
	}
	
	//! Energy manager: Returns true if this device can be plugged into the given energy source. Otherwise returns false.
	bool CanBePluggedInto( EntityAI potential_energy_provider )
	{
		return potential_energy_provider.GetCompEM().CanReceivePlugFrom( m_ThisEntityAI );
	}
	
	//! Energy manager: Returns true if the electricity icon (bolt) is supposed to be visible for this device. False if not.
	bool HasElectricityIcon()
	{
		return m_HasElectricityIcon;
	}
	
	//! Energy manager: Returns true if this item automatically converts its energy to quantity
	bool HasConversionOfEnergyToQuantity()
	{
		return m_ConvertEnergyToQuantity;
	}

	/**
	\brief Energy manager: Returns true if this device's virtual power cord can reach its energy source at the given position, depending on its cordLength config parameter. Otherwise returns false.
		\param from_position \p vector position from where the measurement will be taken
		\param add_tolerance \p float parameter will add to the cord's length in meters (optional)
		\return \p bool True if the power source will be at reach for the plug, or if config param cordLength is absent or 0. False if not, or is not plugged, or this device lacks Energy Manager component.
		@code
			vector position_player = GetGame().GetPlayer().GetPosition();
			
			if ( my_device.GetCompEM().IsEnergySourceAtReach( position_player )  )
			{
				Print("Power source is at reach!");
			}else{
				Print("Power source is NOT at reach!");
			}
		@endcode
	*/
	bool IsEnergySourceAtReach( vector from_position, float add_tolerance = 0, vector override_source_position = "-1 -1 -1" )
	{
		if ( !IsPlugged()  &&  override_source_position == "-1 -1 -1" )
		{
			return false;
		}
		
		if ( GetCordLength() == 0 ) // 0 is an exception, which means infinitely long cable.
		{
			return true;
		}
		
		vector source_pos;
		float distance;
		
		if ( override_source_position == "-1 -1 -1" )
		{
			EntityAI energy_source = GetEnergySource();
			
			if (!energy_source)
				return false;
			
			source_pos = energy_source.GetPosition();
			distance = vector.Distance( from_position, source_pos );
		}
		else
		{
			source_pos = override_source_position;
			distance = vector.Distance( from_position, source_pos );
		}
		
		if (distance > GetCordLength() + add_tolerance)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	bool HasVisibleSocketsInInventory()
	{
		return m_ShowSocketsInInventory;
	}
	
	//! Energy manager: Returns true if this selection is a plug that's plugged into this device. Otherwise returns false.
	bool IsSelectionAPlug(string selection_to_test )
	{
		if ( GetPluggedDevices() )
		{
			int socket_count = GetSocketsCount();
			
			for ( int i = socket_count; i >= 0; --i )
			{
				string real_selection = SOCKET_ + i.ToString() +_PLUGGED;
				
				if ( selection_to_test == real_selection)
				{
					return true;
				}
			}
		}
		
		return false;
	}
	
	
	
	
	//! Energy manager: Returns the count of power sockets (whenever used or not)
	int GetSocketsCount()
	{
		return m_SocketsCount;
	}

	//! Energy manager: Returns plug type. Check \DZ\data\basicDefines.hpp  OR  \Scripts\Classes\Component\_constants.h files for types of plugs
	int GetPlugType()
	{
		return m_PlugType;
	}

	// Returns the action ID which is supposed to be done upon receiving an attachment
	int GetAttachmentAction()
	{
		return m_AttachmentActionType;
	}

	// Returns persistent ID (block 1) of the energy source
	int GetEnergySourceStorageIDb1()
	{
		return m_EnergySourceStorageIDb1;
	}

	// Returns persistent ID (block 2) of the energy source
	int GetEnergySourceStorageIDb2()
	{
		return m_EnergySourceStorageIDb2;
	}
	
	// Returns persistent ID (block 3) of the energy source
	int GetEnergySourceStorageIDb3()
	{
		return m_EnergySourceStorageIDb3;
	}
	
	// Returns persistent ID (block 4) of the energy source
	int GetEnergySourceStorageIDb4()
	{
		return m_EnergySourceStorageIDb4;
	}
	
	// Returns network ID (low) of the energy source
	int GetEnergySourceNetworkIDLow()
	{
		return m_EnergySourceNetworkIDLow;
	}

	// Returns network ID (high) of the energy source
	int GetEnergySourceNetworkIDHigh()
	{
		return m_EnergySourceNetworkIDHigh;
	}
	
	//! Energy manager: Returns the number of devices plugged into this one.
	int GetPluggedDevicesCount()
	{
		if ( GetPluggedDevices() )
		{
			return GetPluggedDevices().Count();
		}
		
		return 0;
	}
	
	//! Energy manager: Returns % of stored energy this device has as integer (from 0 to 100)
	int GetEnergy0To100()
	{
		if ( m_EnergyStorageMax > 0 )
		{
			int coef = Math.Round( m_Energy / m_EnergyStorageMax * 100 );
			return coef;
		}
		
		return 0;
	}
	
	//! Energy manager: Returns % of stored energy this device has as float (from 0.0 to 1.0)
	float GetEnergy0To1()
	{
		if ( m_EnergyStorageMax > 0 )
		{
			return m_Energy / m_EnergyStorageMax;
		}
		
		return 0;
	}
	
	//! Energy manager: Returns the update interval of this device.
	float GetUpdateInterval()
	{
		#ifdef DIAG_DEVELOPER
		if (FeatureTimeAccel.GetFeatureTimeAccelEnabled(ETimeAccelCategories.ENERGY_CONSUMPTION) || (FeatureTimeAccel.GetFeatureTimeAccelEnabled(ETimeAccelCategories.ENERGY_RECHARGE)))
		{
			return 1;//when modifying time accel, we might want to see things happen when they should, instead of waiting for the next tick
		}
		#endif
		return m_UpdateInterval;
	}
	
	//! Returns wetness exposure value defined in config
	float GetWetnessExposure()
	{
		return m_WetnessExposure;
	}
	
	//! Energy manager: Returns the number of energy this device needs to run itself (See its config >> energyUsagePerSecond)
	float GetEnergyUsage()
	{
		return m_EnergyUsage;
	}

	//! Energy manager: Returns the amount of stored energy this device has
	float GetEnergy()
	{
		return m_Energy;
	}

	//! Energy manager: Adds energy to this device and clamps it within its min/max storage limits. Returns the amount of energy that was clamped. Negative value is supported, but you should still use ConsumeEnergy(...) for propper substraction of energy.
	float AddEnergy(float added_energy)
	{
		if (added_energy != 0)
		{
			//Print("AddEnergy ---------> " + added_energy + " " + this + " " +m_ThisEntityAI.ClassName());
			#ifdef DIAG_DEVELOPER
			if (FeatureTimeAccel.GetFeatureTimeAccelEnabled(ETimeAccelCategories.ENERGY_CONSUMPTION) && added_energy < 0)
			{
				float timeAccel = FeatureTimeAccel.GetFeatureTimeAccelValue();
				added_energy *= timeAccel;
			}
			#endif
			
			bool energy_was_added = (added_energy > 0);
			
			float energy_to_clamp = GetEnergy() + added_energy;
			float clamped_energy = Math.Clamp( energy_to_clamp, 0, GetEnergyMax() );
			SetEnergy(clamped_energy);
			StartUpdates();
			
			if (energy_was_added)
				OnEnergyAdded();
			else
				OnEnergyConsumed();
			
			return energy_to_clamp - clamped_energy;
		}
		
		return 0;
	}
	
	//! Energy manager: Returns the maximum amount of energy this device can curently store. If parameter 'reduceMaxEnergyByDamageCoef' is used in the config of this device then the returned value will be reduced by damage.
	float GetEnergyMax()
	{
		float max_health = 0;
		
		if ( m_ThisEntityAI.HasDamageSystem() )
			max_health = m_ThisEntityAI.GetMaxHealth("","");
		//else if ( m_ReduceMaxEnergyByDamageCoef != 0 )
		//	Error("[ERROR] ReduceMaxEnergyByDamageCoef is setup but " + m_ThisEntityAI.GetType() + " does not have a Damage System");
		
		if ( max_health == 0 || m_ReduceMaxEnergyByDamageCoef == 0 )
			return GetEnergyMaxPristine();
		
		float health = 100;
		
		if (GetGame().IsServer() || !GetGame().IsMultiplayer()) // TO DO: Remove this IF when method GetHealth can be called on client!
			health = m_ThisEntityAI.GetHealth("","");
		
		float damage_coef = 1 - (health / max_health);
		
		return GetEnergyMaxPristine() * (1 - ( damage_coef * m_ReduceMaxEnergyByDamageCoef ) );
	}
	
	//! Energy manager: Returns the maximum amount of energy this device can store. It's damage is NOT taken into account.
	float GetEnergyMaxPristine()
	{
		return m_EnergyStorageMax;
	}
	
	float GetEnergyAtSpawn()
	{
		return m_EnergyAtSpawn;
	}
	
	//! Energy manager: Returns the length of the virtual power cord.
	float GetCordLength()
	{
		return m_CordLength;
	}

	//! Energy manager: Returns the energy source this device is plugged into
	EntityAI GetEnergySource()
	{
		return m_EnergySource;
	}
	
	//! Energy manager: Returns the device which is plugged into the given socket ID.
	EntityAI GetDeviceBySocketID(int id)
	{
		return m_Sockets[id];
	}

	//! Energy manager: Returns the device to which the given plug selection belongs to
	EntityAI GetPlugOwner(string plug_selection_name)
	{
		if ( m_DeviceByPlugSelection.Contains(plug_selection_name) )
		{
			return m_DeviceByPlugSelection.Get(plug_selection_name);
		}
		
		return NULL;
	}
	
	//! Energy manager: Returns a device which is plugged into this one. If there are more devices to choose from then it returns the first one that is found.
	EntityAI GetPluggedDevice()
	{
		if ( GetPluggedDevicesCount() > 0 )
		{
			return GetPluggedDevices().Get(0);
		}
		
		return NULL;
	}
	
	//! Energy manager: Returns path to the cord texture file.
	string GetCordTextureFile()
	{
		return m_CordTextureFile;
	}

	//! Energy manager: Returns an array of devices which are plugged into this one
	array<EntityAI> GetPluggedDevices()
	{
		return m_PluggedDevices;
	}

	//! Energy manager: Returns an array of devices which are plugged into this one and are turned on
	array<EntityAI> GetPoweredDevices()
	{
		array<EntityAI> return_array = new array<EntityAI>;
		int plugged_devices_c = GetPluggedDevicesCount();
		for ( int i = 0; i < plugged_devices_c; ++i )
		{
			EntityAI device = GetPluggedDevices().Get(i);
			if ( IsSwitchedOn() )
			{
				return_array.Insert(device);
			}
		}
		
		return return_array;
	}
	
	
	/*===================================
				PUBLIC EVENTS
	===================================*/

	// Called every device update if its supposed to do some work. The update can be every second or at random, depending on its manipulation.
	void OnWork( float consumed_energy ) 
	{
		m_ThisEntityAI.OnWork(consumed_energy);
	}

	// Called when this device is plugged into some energy source
	void OnIsPlugged(EntityAI source_device) 
	{
		if (m_DebugPlugs)
		{
			if (!m_DebugUpdate)
				m_DebugUpdate = new Timer( CALL_CATEGORY_SYSTEM );
			
			if (!m_DebugUpdate.IsRunning())
				m_DebugUpdate.Run(0.01, this, "DebugUpdate", NULL, true);
		}
		
		UpdateCanWork();
		m_ThisEntityAI.OnIsPlugged(source_device);
	}

	// Called when this device is UNPLUGGED from the energy source
	void OnIsUnplugged( EntityAI last_energy_source ) 
	{
		UpdateCanWork();
		m_ThisEntityAI.OnIsUnplugged( last_energy_source );
	}

	// When something is plugged into this device
	void OnOwnSocketTaken( EntityAI device ) 
	{
		//play sound
		if ( device.GetCompEM().GetPlugType() == PLUG_COMMON_APPLIANCE && m_ThisEntityAI.IsInitialized() )
		{
			EffectSound sound_plug;
			m_ThisEntityAI.PlaySoundSet( sound_plug, "cablereel_plugin_SoundSet", 0, 0 );
		}
		
		m_ThisEntityAI.OnOwnSocketTaken(device);
	}

	// When something is UNPLUGGED from this device
	void OnOwnSocketReleased( EntityAI device ) 
	{
		//play sound
		if ( device.GetCompEM().GetPlugType() == PLUG_COMMON_APPLIANCE && m_ThisEntityAI.IsInitialized() )
		{
			EffectSound sound_unplug;
			m_ThisEntityAI.PlaySoundSet( sound_unplug, "cablereel_unplug_SoundSet", 0, 0 );
		}
				
		m_ThisEntityAI.OnOwnSocketReleased( device );
	}
	
	
	// Handles automatic attachment action
	void OnAttachmentAdded(EntityAI elec_device)
	{
		int attachment_action_type = GetAttachmentAction();
		
		if ( attachment_action_type == PLUG_THIS_INTO_ATTACHMENT )
		{
			if ( elec_device.GetCompEM().CanReceivePlugFrom( m_ThisEntityAI ) )
			{
				PlugThisInto(elec_device);
			}
		}
		else if ( attachment_action_type == PLUG_ATTACHMENTS_INTO_THIS )
		{
			elec_device.GetCompEM().PlugThisInto(m_ThisEntityAI);
		}
	}

	// Handles automatic detachment action
	void OnAttachmentRemoved(EntityAI elec_device)
	{
		int attachment_action_type = GetAttachmentAction();
		
		if ( attachment_action_type == PLUG_THIS_INTO_ATTACHMENT )
		{
			if ( elec_device == GetEnergySource() )
			{
				UnplugThis();
			}
		}
		else if ( attachment_action_type == PLUG_ATTACHMENTS_INTO_THIS )
		{
			elec_device.GetCompEM().UnplugThis();
		}
	}

	// Starts the device's main cycle
	void StartUpdates()
	{
		if (!m_IsPassiveDevice)
		{
			if (!m_UpdateTimer)
				m_UpdateTimer = new Timer(CALL_CATEGORY_SYSTEM);
			
			if (!m_UpdateTimer.IsRunning()) // Makes sure the timer is NOT running already
			{
				m_UpdateTimer.Run(GetUpdateInterval(), this, "DeviceUpdate", null, true);
			}
		}
	}
	
	//! Energy manager: Called when energy was consumed on this device
	void OnEnergyConsumed()
	{
		m_ThisEntityAI.OnEnergyConsumed();
	}
	
	//! Energy manager: Called when energy was added on this device
	void OnEnergyAdded()
	{
		if (m_UpdateQuantityTimer)
		{
			m_UpdateQuantityTimer.Stop();
			m_UpdateQuantityTimer = NULL;
		}
		
		m_ThisEntityAI.OnEnergyAdded();
	}


	/*===================================
			 PROTECTED FUNCTIONS
	===================================*/

	// Stops the device's main cycle
	protected void StopUpdates()
	{
		if (m_UpdateTimer)
		{
			m_UpdateTimer.Stop();
			m_UpdateTimer = NULL; // Delete timer from memory
		}
	}

	//! Gets called originally when the player is interacting with an item containing this energy component, then recursively following the branches of connection from the original item to the peripheries
	//! External calling of this function is not automatic for all item interactions and may need to be implemented on case by case bases
	//! Avoid using for gameplay logic, use 'OnInteractBranch' instead
	void InteractBranch(EntityAI originalCaller, Man player = null, int system = 0)
	{
		OnInteractBranch(originalCaller, player, system);
		if ( GetSocketsCount() > 0 )
		{
			array<EntityAI> devices = GetPluggedDevices();
			
			foreach ( EntityAI device : devices)
			{
				if ( device != originalCaller ) // originalCaller check here prevents infinite loops
				{
					device.GetCompEM().InteractBranch( originalCaller, player, system );
				}
			}
		}
	}
	
	//! Called when the player is interacting with an item containing this energy component, or when interacting with an item this device is connected to
	protected void OnInteractBranch(EntityAI originalCaller, Man player, int system)
	{
		m_ThisEntityAI.IncreaseLifetime();
	
	}
		
	// 'Wakes up' all devices down the network so they start working, if they have enough power, and are switched ON
	protected void WakeUpWholeBranch( EntityAI original_caller )
	{
		if ( GetSocketsCount() > 0 )
		{
			array<EntityAI> plugged_devices = GetPluggedDevices();
			int plugged_devices_c = plugged_devices.Count();
			
			for ( int i = 0; i < plugged_devices_c; ++i )
			{
				EntityAI device = plugged_devices.Get(i);
				if ( device != original_caller ) // original_caller check here prevents infinite loops
				{
					device.GetCompEM().UpdateCanWork();
					device.GetCompEM().DeviceUpdate();
					device.GetCompEM().StartUpdates();
					device.GetCompEM().WakeUpWholeBranch( original_caller );
				}
			}
		}
	}

	// Finds an available socket and plugs the given device into it.
	// This is mainly about visualisation.
	protected void PlugCordIntoSocket( EntityAI device_to_plug, int socket_id = -1 )
	{
		if (socket_id >= 0)
		{
			EntityAI plug_owner_by_socket = GetDeviceBySocketID(socket_id);
			
			if (!plug_owner_by_socket)
			{
				UpdateSocketSelections(socket_id, device_to_plug);
				return;
			}
		}

		int slots_c = GetSocketsCount();
		
		for ( int i = 0; i < slots_c; ++i )
		{
			EntityAI plug_owner = GetDeviceBySocketID(i);
			
			if ( !plug_owner ) // Check if this socket is available
			{
				UpdateSocketSelections(i, device_to_plug);
				break;
			}
		}
	}
	
	// Updates socket selections (plugged/unplugged) of the given ID and sets color texture of the plug.
	protected void UpdateSocketSelections(int socket_id, EntityAI device_to_plug)
	{
		SetDeviceBySocketID(socket_id, device_to_plug);
		
		string plugged_selection = SOCKET_ + (socket_id+1).ToString() + _PLUGGED;
		SetPlugOwner( plugged_selection, device_to_plug );
		m_ThisEntityAI.ShowSelection ( plugged_selection );
		
		string unplugged_selection = SOCKET_ + (socket_id+1).ToString() + _AVAILABLE;
		m_ThisEntityAI.HideSelection ( unplugged_selection );
		string texture_path = device_to_plug.GetCompEM().GetCordTextureFile();
		int selection_index = m_ThisEntityAI.GetHiddenSelectionIndex( plugged_selection );
		m_ThisEntityAI.SetObjectTexture( selection_index, texture_path );
		device_to_plug.GetCompEM().SetMySocketID(socket_id);
	}
	
	
	// Sets energy source for this device
	protected void SetEnergySource( EntityAI source )
	{	
		m_EnergySource = source;
		
		if (source)
		{
			m_IsPlugged = true;
			StartUpdates();
		}
		else
		{
			m_IsPlugged = false;
			m_EnergySourceNetworkIDLow = -1;
			m_EnergySourceNetworkIDHigh = -1;
		}
		
		if (m_EnergySource)
			m_EnergySource.GetNetworkID(m_EnergySourceNetworkIDLow, m_EnergySourceNetworkIDHigh);
		
		Synch();
	}

	// Plugs the given device into this one
	protected bool PlugInDevice(EntityAI device_to_plug, int socket_id = -1)
	{
		if (CanReceivePlugFrom(device_to_plug))
		{
			device_to_plug.IncreaseLifetime();
			InteractBranch(m_ThisEntityAI);
			if (device_to_plug.GetCompEM().IsPlugged())
				device_to_plug.GetCompEM().UnplugThis();
			
			GetPluggedDevices().Insert(device_to_plug);
			device_to_plug.GetCompEM().SetEnergySource(m_ThisEntityAI);
			
			PlugCordIntoSocket(device_to_plug, socket_id); // Visualisation
			OnOwnSocketTaken(device_to_plug);
			
			device_to_plug.GetCompEM().OnIsPlugged(m_ThisEntityAI);
			WakeUpWholeBranch( m_ThisEntityAI );
			
			if (GetGame().IsServer() || !GetGame().IsMultiplayer())
			{
				device_to_plug.HideSelection(SEL_CORD_FOLDED);
				device_to_plug.ShowSelection(SEL_CORD_PLUGGED);
			}
			
			return true;
		}
		
		return false;
	}

	// Sets the device to which the given plug selection belongs to
	protected void SetPlugOwner(string selection_name, EntityAI device)
	{
		if ( m_DeviceByPlugSelection.Contains(selection_name) )
		{
			m_DeviceByPlugSelection.Set(selection_name, device);
		}
	}
	
	// Frees the given socket.
	// This is only about visualisation.
	protected void UnplugCordFromSocket( int socket_to_unplug_ID )
	{
		EntityAI plug_owner = GetDeviceBySocketID(socket_to_unplug_ID);
		
		if ( plug_owner )
		{
			SetDeviceBySocketID(socket_to_unplug_ID, NULL);
			string unplugged_selection = SOCKET_ + (socket_to_unplug_ID+1).ToString() + _AVAILABLE;
			m_ThisEntityAI.ShowSelection ( unplugged_selection );
			
			string plugged_selection = SOCKET_ + (socket_to_unplug_ID+1).ToString() + _PLUGGED;
			m_ThisEntityAI.HideSelection ( plugged_selection );
			SetPlugOwner( plugged_selection, NULL );
			plug_owner.GetCompEM().SetMySocketID(-1);
		}
	}

	// Sets the state of the device
	protected void SetPowered( bool state )
	{
		m_IsWorking = state;
	}
	
	// Tries to consume the given amount of energy. If there is none in this device, then it tries to take it from some power source.
	protected bool FindAndConsumeEnergy(EntityAI original_caller, float amount, bool ignore_switch_state = false)
	{
		if ( (ignore_switch_state  ||  IsSwitchedOn())  &&  !m_ThisEntityAI.IsRuined() )
		{
			float available_energy = AddEnergy(-amount);
			
			if ( available_energy < 0  &&  IsPlugged() )
			{
				// This devices does not has enough of stored energy, therefore it will take it from its power source (which can be a chain of cable reels)
				EntityAI next_power_source = GetEnergySource();
				
				if (next_power_source  &&  next_power_source != original_caller) // Prevents infinite loop if the power source is the original caller itself
				{
					return next_power_source.GetCompEM().FindAndConsumeEnergy( original_caller, -available_energy );
				}
			}
			
			if ( available_energy >= 0)
			{
				return true;
			}
			
			return false;
		}
		else
		{
			return false;
		}
	}
	
	// Gets the socket ID this device is powered from.
	protected int GetMySocketID()
	{
		return m_MySocketID;
	}
	
	// Sets the socket ID this device is plugged into.
	protected void SetMySocketID( int slot_ID )
	{
		m_MySocketID = slot_ID;
	}

	void Synch()
	{
		m_ThisEntityAI.SetSynchDirty();
	}
	
	void ClearLastUpdateTime()
	{
		m_LastUpdateTime = 0;
	}
	
	void RememberLastUpdateTime()
	{
		m_LastUpdateTime = GetCurrentUpdateTime();
	}
	
	float GetCurrentUpdateTime()
	{
		return GetGame().GetTime();
	}
	
	// Updates the device's state of power. This function is visualized in the diagram at DayZ Confluence >> Camping & Squatting >> Electricity >> Energy Manager functionalities
	void DeviceUpdate()
	{
		/*
		vector pos = m_ThisEntityAI.GetPosition();
		string debug_message = "Object " + m_ThisEntityAI.GetType() + "  |  Energy: " + GetEnergy() + "  |  IsAtReach: " + (IsEnergySourceAtReach(pos)).ToString();
		Print(debug_message);
		*/
		
		if ( !m_IsPassiveDevice )
		{
			// 'm_ThisEntityAI' and 'this' must be checked because this method is caled from a timer
			if ( m_ThisEntityAI  &&  this  &&  IsSwitchedOn()  &&  !m_ThisEntityAI.IsRuined()  &&  CheckWetness()  &&  m_CanWork  &&  !GetGame().IsMissionMainMenu() )
			{
				bool was_powered = IsWorking();
				float consumed_energy_coef;
				// Make sure to use only as much % of energy as needed since this function can be called at random.
				
				if ( m_LastUpdateTime == 0 )
				{
					RememberLastUpdateTime();
					consumed_energy_coef = 1.0;
				}
				else
				{
					float updatetime = GetCurrentUpdateTime();
					float time = updatetime - m_LastUpdateTime;
					consumed_energy_coef = time / 1000;
				}
				
				if (consumed_energy_coef > 0) // Prevents calling of OnWork events when no energy is consumed
				{
					m_LastUpdateTime = GetCurrentUpdateTime();
					float consume_energy = GetEnergyUsage() * consumed_energy_coef;
					bool has_consumed_enough = true;
					
					if (GetGame().IsServer() || !GetGame().IsMultiplayer()) // single player or server side multiplayer
						has_consumed_enough = ConsumeEnergy( consume_energy );
					
					SetPowered( has_consumed_enough );
					
					if ( has_consumed_enough )
					{
						if ( !was_powered )
						{
							m_CanStopWork = true;
							WakeUpWholeBranch(m_ThisEntityAI);
							GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnWorkStart", NULL, 0);
							UpdateCanWork();
						}
						
						OnWork( consume_energy );
					}
					else
					{
						if ( was_powered )
						{
							if (m_CanStopWork)
							{
								m_CanStopWork = false;
								ClearLastUpdateTime();
								GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnWorkStop", NULL, 0); // This event is called only once when the device STOPS being powered
								UpdateCanWork();
								
								if (m_AutoSwitchOff)
								{
									SwitchOff(); 
								}
							}
						}
						
						StopUpdates();
					}
				}
				else
				{
					ClearLastUpdateTime();
				}
			}
			else if (this && m_ThisEntityAI)
			{
				SetPowered( false );
				StopUpdates();
				
				if (m_CanStopWork)
				{
					m_CanStopWork = false;
					ClearLastUpdateTime();
					GetGame().GameScript.CallFunction(m_ThisEntityAI, "OnWorkStop", NULL, 0); // This event is called only once when the device STOPS being powered
					UpdateCanWork();
					
					if (m_AutoSwitchOff)
					{
						SwitchOff(); 
					}
				}
			}
		}
	}
}