-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdrone
executable file
·1880 lines (1606 loc) · 51.3 KB
/
drone
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
-- libdrone
-- if digArea is digging a 2 high area, the drone should traverse on the upper layer, right
-- now it will traverse the lower layer digging upwards - this is bad for farming, ie sugar canes
-- which will break of and drop if the middle part is dug before the top part.
drone = {}
version = "0.1"
os.loadAPI("swarm")
swarm.setSystemType("drone")
DRONE_MAP_CACHE_TIMEOUT = 12000
DRONE_LONGLOOP_YIELD_COUNT = 1000
quit = false
abort = false
unloaded = 0
collected = 0
pos = {0,0,0}
xDir,yDir,zDir = 0,-1,0
startTime = swarm.timestamp()
id = os.getComputerID()
os.setComputerLabel(swarm.getSystemType().." "..id)
label = os.getComputerLabel()
navmap = map.new()
dronePositions = {}
paths = {}
fuelLevel = -1
fuelLimit = -1
config = {}
counters = {0,0,0,0}
-- Some defaults for the config
-- You may want to adjust the default mapServerID
-- TODO: use default.config file instead
config["mapServerID"] = 43
config["homePos"] = {6,6,6,0}
config["storagePos"] = {6,6,6,1}
config["jobPos"] = {6,6,6,2}
-- Menu vars
local selected = 1
local actions = {"abort","home","unload","recharge"}
local useMinyMod = false
local miny = false
function navmap:set2(x,y,z,v)
-- Send message of type 3 (set worldmap value) to mapserver
rednet.send(config["mapServerID"],string.char(3)..textutils.serialize({x,y,z,v}))
-- Set value in local cache with current timestamp
navmap:set(x,y,z,{swarm.timestamp(),{v,1}})
end
function navmap:get2(x,y,z,cacheonly)
cacheonly = cacheonly or false
-- Check local cache if we have a recent entry
local v = navmap:get(x,y,z)
if v ~= nil and v[1] ~= nil then
-- Check if age is below timelimit
if swarm.timestamp() - v[1] <= DRONE_MAP_CACHE_TIMEOUT then
-- Cache hit, return value
counters[1] = counters[1] + 1
return v[2]
end
--TODO: Clear values to save mem in case of worldMap reset while drone is running?
--navmap:set(x,y,z,nil)
v = v[2]
end
if cacheonly then
return v
end
-- Cache miss, request value from mapserver.
counters[4] = counters[4] + 1
local id,msg,dist
local repeats = 0
-- Prepare query of type 1 (get value from worldmap)
local request = string.char(1).."{"..x..","..y..","..z.."}"
swarm.openModem(swarm.id)
-- Send query to mapserver
rednet.send(config["mapServerID"],request)
local event,side,id,rid,msg,info,dist
local timeout = os.startTimer(4)
-- Wait for response
while true do
if repeats > 0 then
swarm.status("waiting for response from mapserver "..config["mapServerID"].." [repeat: "..repeats.."]")
if repeats > 10 then
return v
end
end
local e = {os.pullEvent()}
if e[1] == "timer" and e[2] == timeout then
-- Resend request
rednet.send(config["mapServerID"],request)
timeout = os.startTimer(4)
-- Keep trying forever
repeats = repeats + 1
elseif e[1] == "modem_message" then
id = e[3]
msg = e[5]["message"]
if e[4] == config["mapServerID"] and e[3] == id and msg:byte(1) == 2 then
v = textutils.unserialize(string.sub(msg,2))
if v ~= nil and type(v) == "table" then
counters[2] = counters[2] + 1
end
navmap:set(x,y,z,{swarm.timestamp(),v})
counters[3] = counters[3] + 1
return v
end
end
end
return v
end
function navmap:bufferArea(minX,minY,minZ,maxX,maxY,maxZ)
swarm.status("buffering mapdata ...")
if maxY == nil then
local range = maxX
maxX = minX+range
maxY = minY+range
maxZ = minZ+range
minX = minX-range
minY = minY-range
minZ = minZ-range
end
local data = nil
local id,msg,dist = 0,string.char(4)..textutils.serialize({{minX,minY,minZ},{maxX,maxY,maxZ}}),0
-- Send query to mapserver
rednet.send(config["mapServerID"],msg)
-- Wait for response
while true do
id,msg,dist = rednet.receive(120)
if id == nil then
log("error: no signal from mapserver")
break
end
if string.byte(msg) == 5 and id == config["mapServerID"] then
data = textutils.unserialize(string.sub(msg,2))
break
end
end
if data ~= nil then
for k,v in pairs(data) do
--sleep(0) -- MARKMARK--
navmap:set(v[1],v[2],v[3],{swarm.timestamp(),v[4]})
end
end
return v
end
-- Simple wrapper for turtle function so we remember our direction
function turnLeft()
turtle.turnLeft()
xDir, yDir = -yDir, xDir
end
-- Simple wrapper for turtle function so we remember our direction
function turnRight()
turtle.turnRight()
xDir, yDir = yDir, -xDir
end
function getFuelLevel()
return turtle.getFuelLevel()
end
function getFuelLimit()
return turtle.getFuelLimit()
end
function calibrateSub(turns)
x,y,z = gps.locate(1)
while x == nil or (x==0 and y==0 and z==0) do
swarm.status("orienting: no gps signal! A",true)
print("no gps - cannot calibrate\n")
x,y,z = gps.locate(1,true)
sleep(1)
end
print("...")
local xPos,yPos,zPos = 0,0,0
local up = true
if not turtle.forward() then
-- maybe no fuel!
if x ~= nil then -- we have gps?!
if getFuelLevel() == 0 then
swarm.status("orienting: out of fuel, trying to refuel...",true)
swarm.status("refueled "..consumeAllFuel().." fuels.",true)
if getFuelLevel() == 0 then
swarm.status("orienting: out of fuel at "..x..","..y..","..z.." - NEED HELP!")
return -2
end
sleep(1)
end
--recharge()
end
--log("no fuel?")
return -1
else
xPos,yPos,zPos = gps.locate(1)
while xPos == nil or xPos == math.nan do
if xPos == math.nan then
swarm.status("orienting: faulty gps signal, not enough stations!")
log(swarm.__status.."\n")
else
swarm.status("orienting: no gps signal! B")
log(swarm.__status.."\n")
end
xPos,yPos,zPos = gps.locate(4,true)
sleep(1)
end
print("gps: "..xPos..","..yPos..","..zPos)
turtle.back()
end
if x == nil or xPos == nil then
return -2
end
pos[1] = x
pos[2] = y
pos[3] = z
if xPos == pos[1] and yPos == pos[2] and zPos == pos[3] then
return -1
end
xDir = xPos - pos[1]
yDir = yPos - pos[2]
zDir = 0 --zPos - pos[3]
--print("get direction "..xDir.." "..yDir.." "..xPos.." "..yPos)
local dir = swarm.getDirection(xDir,yDir,zDir) - turns
if dir > 3 then dir = dir - 4 end
if dir < 0 then dir = dir + 4 end
turnRot(dir)
-- Broadcast our current position
-- rednet.broadcast(string.char(10)..textutils.serialize({pos[1],pos[2],pos[3],swarm.status}))
return 1
end
-- Orients the turtle in GPS-space and determines current direction
function calibrate()
local m = 0 -- calibrateSub(0)
local turns = 0
local up = true
local back = ""
while m ~= 1 do
if m == -2 then
swarm.status("orienting: no gps signal, waiting!",true)
sleep(4)
elseif m == -3 then
swarm.status("orienting: no fuel, waiting",true)
sleep(4)
else
swarm.status("orienting: got gps, trying",true)
if turns < 4 then
print(0)
turtle.turnRight()
print(1)
turns = turns + 1
print(2)
else
turns = 0
if up then
if not turtle.up() then
up = false
end
else
if not turtle.down() then
swarm.status("orienting: stuck @ "..x..","..y..","..z.." - NEED HELP!",true)
up = true
end
end
end
print(3)
end
print("...")
m = calibrateSub(turns)
sleep(0) -- MARKMARK
end
-- check position
if not checkPositionAgainstGPS() then
swarm.status("failed to calibrate itself")
sleep(30)
return false
end
swarm.status("has calibrated itself @ "..textutils.serialize({pos[1],pos[2],pos[3]}))
return true
end
function turnDir(newXDir,newYDir)
if xDir == newXDir and yDir == newYDir then
return
end
local rot = (swarm.getDirection(xDir,yDir,0) - swarm.getDirection(newXDir,newYDir,0))
-- Make sure we use the shortest direction to get where we want
if rot > 2 then
rot = rot - 4
elseif rot < -2 then
rot = rot + 4
end
while rot ~= 0 do
if rot < 0 then
turnRight()
rot = rot + 1
end
if rot > 0 then
turtle.turnLeft()
rot = rot - 1
end
end
xDir = newXDir
yDir = newYDir
end
function turnRot(dir)
if dir < 0 then
err("BUG: turnRot < 0")
end
if dir < 4 then
turnDir(swarm.xDirs[dir],swarm.yDirs[dir],0)
end
end
-- Tries to move a single step in the specified direction
function goDir(dir)
if dir == 5 then
return turtle.down()
elseif dir == 4 then
return turtle.up()
else
turnRot(dir)
return turtle.forward()
end
end
function dropDir(dir,count)
count = count or 64
if dir == 5 then
return turtle.dropDown(count)
elseif dir == 4 then
return turtle.dropUp(count)
else
turnRot(dir)
return turtle.drop(count)
end
end
-- Performs a single detect in the specified direction
function detectDir(dir)
--print("CHECK1")
-- Check if some other turtle is in that direction
local target = {pos[1]+swarm.xDirs[dir],pos[2]+swarm.yDirs[dir],pos[3]+swarm.zDirs[dir]}
if isOtherDroneAtPos(target) then
swarm.status("detected other turtle at "..textutils.serialize(target))
return -1
end
if dir == 5 then
return turtle.detectDown() and 1 or 0
elseif dir == 4 then
return turtle.detectUp() and 1 or 0
else
turnRot(dir)
return turtle.detect() and 1 or 0
end
end
-- Performs a single attack in the specified direction
function attackDir(dir)
if dir == 5 then
return turtle.attackDown()
elseif dir == 4 then
return turtle.attackUp()
else
turnRot(dir)
return turtle.attack()
end
end
-- Performs a single dig in the specified direction
function digDir(dir)
if dir == 5 then
return turtle.digDown()
elseif dir == 4 then
return turtle.digUp()
else
turnRot(dir)
return turtle.dig()
end
end
function digDirMiny(dir)
if dir == 5 then
return miny.digDown()
elseif dir == 4 then
return miny.digUp()
else
turnRot(dir)
return miny.dig()
end
end
-- Performs a single suck in the specified direction
function suckDir(dir)
if dir == 5 then
return turtle.suckDown()
elseif dir == 4 then
return turtle.suckUp()
else
turnRot(dir)
return turtle.suck()
end
end
-- Sucks in each direction
function suckAll()
local r = false
for i = 0,5,1 do
if suckDir(i) then
r = true
end
end
end
-- Compare selected slot with block in the specified direction
function compareDir(dir)
if dir == 5 then
return turtle.compareDown()
elseif dir == 4 then
return turtle.compareUp()
else
turnRot(dir)
return turtle.compare()
end
end
-- Broadcast our current position and status
function broadcast()
local msg
navmap:set(pos[1],pos[2],pos[3],{swarm.timestamp(),{0,1}})
msg = "{"..(pos[1])..","..(pos[2])..","..(pos[3])..","..(string.format("%q",swarm.__status))..',["unloaded"]='..(unloaded)..',["uptime"]='..((swarm.timestamp()-startTime)/20).."}"
rednet.send(swarm.CHANNEL_DRONE_BROADCAST,string.char(10)..msg)
--os.setComputerLabel("drone "..id.." "..swarm.activityIndicator())
--print(textutils.serialize(_status))
return true
end
-- Try to move towards the specified direction, detecting and attacking
-- when we hit an obstacle. Stores obstacles in the worldMap.
function go(dir)
if turtle.getFuelLevel() <= 1 then
swarm.status("Out of fuel while moving! Trying to refuel on the go.")
while not consumeAllFuel() > 0 do
swarm.status("Out of fuel while moving! Give me fuel!")
end
end
local counter = 0
local d = 0
local i = 0
while not goDir(dir) do
sleep(0) -- MARKMARK--
d = detectDir(dir)
if d == 1 then -- Could not go there, because a block is blocking our spot
swarm.status("Cannot go there: blocked.")
navmap:set2(pos[1]+swarm.xDirs[dir],pos[2]+swarm.yDirs[dir],pos[3]+swarm.zDirs[dir],1)
return 0
elseif d == 0 then
swarm.status("Cannot go there: mob or player.")
attackDir(dir)
elseif d == -1 then
swarm.status("Cannot go there: other drone.")
return -2
-- sleep(1)
-- do not attack other drones
end
counter = counter + 1
if counter > 4 then
if d == 0 then
swarm.status("path blocked by mob or player!")
return -1
elseif d == -1 then
swarm.status("path blocked by other drone!")
return -2
end
end
swarm.status("loop: "..textutils.serialize(i))
i = i + 1
end
swarm.status("go: ok")
pos[1] = pos[1] + swarm.xDirs[dir]
pos[2] = pos[2] + swarm.yDirs[dir]
pos[3] = pos[3] + swarm.zDirs[dir]
broadcast()
--sleep(0) -- MARKMARK--
return 1
end
--[[
go()/goPath() return values:
1 OK, target reached
0 Detected wall, cannot go there
-1 Mob or Player
-2 Other drone
]]--
goProblems = {[1]="OK - target reached",[0]="FAILURE - detected wall",[-1]="FAILURE - blocked by mob or player",[-2]="FAILURE - blocked by other drone"}
-- Try to move along a known path
function goPath(path)
-- We already are where we wanted to go, nothing to do here
if #path == 0 then
return 1
end
local r
-- Follow the yellow brick road
for i=#path,1,-1 do
if i % DRONE_LONGLOOP_YIELD_COUNT == 0 then sleep(0) end -- MARKMARK--
if #path > 1 then swarm.status("following path, step "..i.." / "..#path) end
r = go(path[i])
if r ~= 1 then
swarm.status("could not follow path at step "..i.." / "..#path..", reason: "..goProblems[r])
local npos = {pos[1],pos[2],pos[3]}
npos[1] = npos[1] + swarm.xDirs[path[i]]
npos[2] = npos[2] + swarm.yDirs[path[i]]
npos[3] = npos[3] + swarm.zDirs[path[i]]
return r,npos
end
-- print("ok")
end
swarm.status("followed path of length "..#path)
return 1
end
-- This checks the table of drone-positions for any drones
-- at the specified position.
function isOtherDroneAtPos(xx,yy,zz)
local x,y,z
if yy == nil then
x,y,z = xx[1],xx[2],xx[3]
else
x = xx
y = yy
z = zz
end
for k,v in pairs(dronePositions) do
--sleep(0) -- MARKMARK--
if v[1] == x and v[2] == y and v[3] == z then
return true
end
end
return false
end
function quickPath(target)
local dir = -1
local path = {}
local tmpPos = {pos[1],pos[2],pos[3]} -- copy
while tmpPos[1] ~= target[1] or tmpPos[2] ~= target[2] or tmpPos[3] ~= target[3] do
swarm.status("calculating direct path: "..#path)
--sleep(0) -- MARKMARK--
dir = lookAtDir(target,tmpPos)
if dir < 0 then return path end
path[#path+1] = dir
tmpPos[1] = tmpPos[1] + swarm.xDirs[dir]
tmpPos[2] = tmpPos[2] + swarm.yDirs[dir]
tmpPos[3] = tmpPos[3] + swarm.zDirs[dir]
end
return path
end
-- Compare current position to valid GPS position and warn if
-- there is a difference. If so this either means a bug, or
-- your GPS is faulty or out of range.
function checkPositionAgainstGPS()
local x,y,z = gps.locate(30)
if x~= nil and (pos[1] ~= x or pos[1] ~= x or pos[1] ~= x) then
print("WARNING: Position not synced anymore!")
print("GPS: "..x..","..y..","..z)
print("LOCAL: "..pos[1]..","..pos[2]..","..pos[3])
sleep(3600)
print(""..nil)
return false
elseif x== nil then
print("WARNING: No connection to gps!")
end
return true
end
function findPath(target)
local posMin,posMax,isArea
posMin = target
posMax = {}
if target[6] ~= nil then
posMax[1] = target[4]
posMax[2] = target[5]
posMax[3] = target[6]
isArea = true
else
posMax = target
isArea = false
end
swarm.status("findPath() 0 area:"..textutils.serialize(isArea).." "..textutils.serialize({target,posMin,posMax}))
-- Already at target position?
if swarm.isWithin(pos,posMin,posMax) then
return {}
end
swarm.status("findPath() 0.1 "..textutils.serialize(pos))
--[[
-- Check if we already have a calculated path cached.
local path = paths[textutils.serialize({pos[1],pos[2],pos[3],xPos,yPos,zPos})]
if path ~= nil then
swarm.status(("debug: using cached path"))
return path
else
path = {}
end
--]]
local outer,inner = 0,0
local tscore = 0
local distance = swarm.manhattanDistance(pos,posMin,posMax)
local maxModifier = 16
local minModifier = 0.1
local modifier = math.min(maxModifier,(distance / 10) + minModifier)
swarm.status("findPath() 1 "..target[1]..","..target[2]..","..target[3].." distance: "..distance)
local temporaryBlocked = {}
while not swarm.isWithin(pos,posMin,posMax) do
-- sleep(0) -- MARKMARK--
--checkPositionAgainstGPS()
outer = outer + 1
local buffer = map.new()
-- local closed = map.new()
local queue = heap:new()
local path,current,score
local x,y,z,d,dist,v,m = 0,0,0,0,0,0,0
local qe = false
local xTarget,yTarget,zTarget = pos[1],pos[2],pos[3]
buffer:set(xTarget,yTarget,zTarget,{-1,0})
current = {xTarget,yTarget,zTarget,-1,0,0}
queue:insert(tscore,current)
-- for d=0,5,1 do navmap:set2(pos[1]+swarm.xDirs[d],pos[2]+swarm.yDirs[d],pos[3]+swarm.zDirs[d],detectDir(d)) end
swarm.status(("outerloop 1 "..outer))
while not queue:empty() and not swarm.isWithin(current,posMin,posMax) do
if inner % DRONE_LONGLOOP_YIELD_COUNT == 0 then sleep(0) end -- MARKMARK--
--checkPositionAgainstGPS()
inner = inner + 1
score,current = queue:pop()
v = navmap:get2(current[1],current[2],current[3],false)
--closed:set(current[1],current[2],current[3],1)
--print(textutils.serialize(v))
--if inner % 100 == 1 then -- less load
swarm.status("innerloop 2 "..inner.." ("..(inner/outer)..") c=".. current[1]..","..current[2]..","..current[3].." dir="..current[4].." dist="..current[5].." score="..score.." q=".. queue:getSize())
--end
if v ~= nil and v[1] == 0 then -- We think this spot is open, no need to actually go there
if isOtherDroneAtPos(current[1],current[2],current[3]) then
local waited = 0
if swarm.isWithin(current,posMin,posMax) then
while isOtherDroneAtPos(current[1],current[2],current[3]) do
swarm.status("other drone at target, waiting. (score: "..(tscore+modifier)..", waited: "..waited..")")
sleep(1)
waited = waited + 1
if waited > 10 then
break
end
end
-- We have waited quite a while, lets go on
end
-- Node is blocked, reinsert it to be looked at at a later time
queue:insert((score+modifier),current)
else
for d=0,5,1 do
if d ~= current[4] then -- skip direction we came from
----sleep(0) -- MARKMARK--
xTarget,yTarget,zTarget = (current[1]+swarm.xDirs[d]), (current[2]+swarm.yDirs[d]), (current[3]+swarm.zDirs[d])
--print(xTarget..","..yTarget..","..zTarget)
m = buffer:get(xTarget,yTarget,zTarget)
if m == nil or m[2] > current[5]+1+(swarm.diffRot(swarm.reverseDirs[current[4]],d)/4) then -- was > before
-- if swarm.diffRot(swarm.reverseDirs[current[4]],d) > 0 then swarm.status(swarm.diffRot(swarm.reverseDirs[current[4]],d).." "..swarm.reverseDirs[current[4]].." "..d,true,-200) end
best = {xTarget,yTarget,zTarget,swarm.reverseDirs[d],current[5]+1+(swarm.diffRot(swarm.reverseDirs[current[4]],d)/4),0}
buffer:set(best[1],best[2],best[3],{best[4],best[5]})
if m == nil then
-- A*
--score = swarm.diffRot(swarm.reverseDirs[current[4]],d) + (swarm.heuristicDistance(xPos,yPos,zPos,xTarget,yTarget,zTarget)+swarm.heuristicDistance(pos[1],pos[2],pos[3],xTarget,yTarget,zTarget))
-- Best-First
score = (swarm.diffRot(swarm.reverseDirs[current[4]],d)/4) + swarm.heuristicDistance({xTarget,yTarget,zTarget},posMin,posMax) + (1/zTarget)
if d == 5 then
score = score + 0.5 -- decrease priority for going down -- was 0.5 before
elseif d == 4 then
--score = score + .5 -- decrease priority for going up a little, we prefer higher paths over lower paths
end
if temporaryBlocked[textutils.serialize({best[1],best[2],best[3]})] ~= nil then
score = score + temporaryBlocked[textutils.serialize({best[1],best[2],best[3]})]
end
--local r = closed:get(xTarget,yTarget,zTarget)
--if r == nil or r > score then
queue:insert(score,best)
-- closed:set(xTarget,yTarget,zTarget,score)
--end
end
end
end
end
end
elseif v ~= nil and v[1] == 1 then
--swarm.status("wall at"..textutils.serialize(current),true,-31)
-- print("wall")
-- wall
else
-- don't immediately explore unknown nodes, prefer known paths
if current[6] == 0 then
current[6] = 1
queue:insert(score+modifier,current) -- increase score to be revisited later on
else
-- need to physically explore spot
-- print("explore")
break
end
end
if queue:empty() then
-- swarm.status("queue empty??? at"..os.clock(),true,-21)
qe = true
break
end
end
if not qe then
--swarm.status(("outerloop 2"),true)
if swarm.isWithin(pos,posMin,posMax) then
swarm.status(("reached target?!"))
break
end
--if xPos == current[1] and yPos == current[2] and zPos == current[3] then
swarm.status(("exploring target:"..textutils.serialize(current)))
-- queue = nil
local i = 1
local rDir = current[4]
local tmp = current
local path = {swarm.reverseDirs[rDir]}
path = {}
while tmp[1] ~= pos[1] or tmp[2] ~= pos[2] or tmp[3] ~= pos[3] do
swarm.status("found target, reconstructing path "..i.." "..rDir)
-- sleep(0) -- MARKMARK--
tmp[1] = tmp[1] + swarm.xDirs[rDir]
tmp[2] = tmp[2] + swarm.yDirs[rDir]
tmp[3] = tmp[3] + swarm.zDirs[rDir]
path[i] = swarm.reverseDirs[rDir] --{xTarget,yTarget,zTarget}
if not (tmp[1] ~= pos[1] or tmp[2] ~= pos[2] or tmp[3] ~= pos[3]) then
break
end
m = buffer:get(tmp[1],tmp[2],tmp[3])
rDir = m[1]
i = i+1
end
sleep(0)
swarm.status("found target, reversing path "..i.." "..rDir)
-- Reverse table but not directions -- I change the goPath to read paths from the back, not intuitive, but we save the reversing.
--path = swarm.reverse(path)
swarm.status("found target, walking path "..i.." "..rDir)
r,npos = goPath(path)
if r ~= 1 then -- Could not get there - what if because of wall? no, cannot be because of wall, only if it was just built
local id = textutils.serialize(npos)
if swarm.compare(posMin,posMax) and swarm.compare(npos,posMin) then
swarm.status("blocklist: our only target is blocked! not listing it!",true,-200)
else
if temporaryBlocked[id] == nil then temporaryBlocked[id] = 0 end
temporaryBlocked[id] = temporaryBlocked[id] + modifier
swarm.status("blocklist: "..temporaryBlocked[id].." "..textutils.serialize(npos),true,-200)
end
--queue:insert(score+modifier,npos) -- increase score to be revisited later on
else
distance = swarm.manhattanDistance(pos,posMin,posMax)
modifier = math.min(maxModifier,(distance / 10) + minModifier)
end
--sleep(0) -- MARKMARK--
swarm.status("walked path: "..goProblems[r].." "..swarm.timestamp(),true,-200)
end
end
end
-- This will unload all items either to an inventory in front of the turtle,
-- or drop them to the ground if cannot find or access the inventory.
-- ME-Terms do not work as inventories for turtles.
function unload(dir)
--dir = dir or
swarm.status("unloading items")
local r = false
local count = 0
for n=1,16,1 do
count = turtle.getItemCount(n)
if config["ignoreSlots"] ~= nil then
for i = 1,#config["ignoreSlots"],1 do
if config["ignoreSlots"][i] == n then
count = 0
break
end
end
end
if count > 0 then
turtle.select(n)
-- should not be possible,but i just had a 68 stack, which will produce errors
if dropDir(dir,math.min(64,count)) then
unloaded = unloaded + count
elseif count > 0 then
swarm.status("could not drop "..count.." item(s), maybe target inventory full?",true,-2)
end
end
end
--TODO: Should we try to pickup items that may have fell to the ground here?
--turtle.select(1)
end
-- Our high-level movement function. Use this to move using all the
-- pathfinding-goodness.
function moveTo(target,retries)
retries = retries or -1
if target == nil then
err("BUG: pos is nil")
end
if #target == 7 then
swarm.status("move to "..target[1]..","..target[2]..","..target[3]..","..target[4]..","..target[5]..","..target[6]..","..target[7].." ["..(#target).."] - "..retries.." retries.")
elseif #target == 6 then
swarm.status("move to "..target[1]..","..target[2]..","..target[3]..","..target[4]..","..target[5]..","..target[6].." ["..(#target).."] - "..retries.." retries.")
elseif #target == 4 then
swarm.status("move to "..target[1]..","..target[2]..","..target[3]..","..target[4].." ["..(#target).."] - "..retries.." retries.")
elseif #target == 3 then
swarm.status("move to "..target[1]..","..target[2]..","..target[3].." ["..(#target).."] - "..retries.." retries.")
end
local r = findPath(target)
while not r and (retries < 0 or retries > 0) do
--sleep(0) -- MARKMARK--
--swarm.status = "could not reach "..posName.." and trying again, reason: "..goProblems[r]
r = moveTo(target,0)
retries = retries - 1
end
if r then
-- Only rotate to the specified direction if
-- we have moved successfully
if target[4] ~= nil and target[5] == nil then
turnRot(target[4])
elseif target[7] ~= nil then
turnRot(target[7])
end
--swarm.status = "reached "..posName.."!"
else
--swarm.status = "could not reach "..posName.." and stopped trying, reason: "..goProblems[r]
end
return r
end
-- Our top-level movement function. Tries to move to a named position.
function moveToPos(targetName,retries)
retries = retries or -1
swarm.status("move to "..targetName.." - "..retries.." retries.")
return moveTo(config[targetName],retries)
end
-- Rotate to face a position
function lookAtDir(target,origin)
if origin == nil then
origin = pos
end
local dir = {target[1] - origin[1],target[2] - origin[2],target[3] - origin[3]}
--local dir = {pos[1] - target[1],pos[2] - target[2],pos[3] - target[3]}
local adir = {math.abs(dir[1]),math.abs(dir[2]),math.abs(dir[3])}
if adir[1] > adir[2] then adir[2] = 0 else adir[1] = 0 end
if adir[1] > adir[3] then adir[3] = 0 else adir[1] = 0 end
if adir[2] > adir[3] then adir[3] = 0 else adir[2] = 0 end
if adir[3] ~= 0 then
dir[3] = math.max(-1,math.min(1,dir[3]))
dir[2] = 0
dir[1] = 0
elseif adir[2] ~= 0 then
dir[2] = math.max(-1,math.min(1,dir[2]))
dir[1] = 0
dir[3] = 0
else
dir[1] = math.max(-1,math.min(1,dir[1]))
dir[2] = 0
dir[3] = 0
end
if dir[1] == 0 and dir[2] == 0 and dir[3] == 0 then
dir[2] = -1
swarm.status("bug: looking at current position, no valid direction possible! "..textutils.serialize(odir)..textutils.serialize(dir)..textutils.serialize(adir)..textutils.serialize({pos[1],pos[2],pos[3]})..textutils.serialize(target),true,-100)
end
return swarm.getDirection(dir[1],dir[2],dir[3])
end
-- If we have more than 15 stacks, we consider the turtle stuffed.
-- If we return only when really full, a lot of stuff will be missed.
-- Lets say you have 16 half-full stacks of cobble and come along some diamond...
function needToUnload()
local stacks = 0
local count = 0
for i= 16,1,-1 do