File size: 23,756 Bytes
b6a38d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
DefineClass.ShipmentSquadPreset = {
	__parents = { "Preset" },
	properties = {
		{ id = "SquadName", editor = "text", default = "", translate = true },
		{ id = "IntelTitle", editor = "text", default = "", translate = true },
		{ id = "IntelText", editor = "text", default = "", translate = true },
		{ id = "icon", editor = "ui_image", default = "" },
		{ id = "intel_icon", editor = "ui_image", default = "" },
		{ id = "badge_icon", editor = "ui_image", default = "" },
		{ id = "squad_icon", editor = "ui_image", default = "" },	
		{ id = "squad_icon_2", editor = "ui_image", default = "" },	
		{ id = "item", editor = "combo", items = ClassDescendantsCombo("InventoryItem"), default = "DiamondBriefcase" },	
		{ id = "enemy_squad_def", editor = "combo", items = function (self) return table.keys(EnemySquadDefs, true) end, default = "DiamondBriefcase" },	
		{ id = "EnableConditions", name = "Conditions", editor = "nested_list", default = false, base_class = "Condition", },
		{ id = "weight", editor = "number", default = 100 },
		
		{ category = "Timeline", id = "TimelineEventTitle", editor = "text", default = "", translate = true },
		{ category = "Timeline", id = "TimelineEventText", editor = "text", default = "", translate = true },
		{ category = "Timeline", id = "TimelineEventHint", editor = "text", default = "", translate = true },
	},
	GlobalMap = "ShipmentPresets",
	Documentation = "Defines a squad preset that can be spawned from the diamond briefcase logic in SpawnDynamicDBSquad(). The properties mainly define how the spawned shipment squad will look like in the satellite UI, the condition for spawning the squad and the items and units it consists of.",
}

DefineModItemPreset("ShipmentSquadPreset", {
	EditorName = "Shipment squad preset",
	EditorSubmenu = "Satellite",
})

function DbgShipmentShowMeSourceDest()
	DbgClearSectorTexts()
	for _, s in pairs(gv_Sectors) do
		local text = false
		if s.DBSourceSector then
			text = "Source"
		end
		if s.DBDestinationSector then
			if text then
				text = text .. " "
			end
			text = (text or "") .. "Dest"
		end
		if text then
			DbgAddSectorText(s.Id, text)
		end
	end
end

-- Move to settings? Per campaign?
local lMaxStaticSquads = 3
local lMinDynamicSquadRouteLength = 10
local lMaxDynamicSquads = 2
local lDynamicSquadDayCooldown = 3
local lDynamicSquadDayChanceToSpawn = 7 -- Is accumulated every day the squad doesn't spawn.
DynamicSquadSpawnChanceOnScout = 25

-- Spawns static diamond shipment squads at the start of the campaign on
-- random sectors
function InitDiamondBriefcaseSquads(guaranteed_spawn)
	local viableSectors = {}
	for id, sector in sorted_pairs(gv_Sectors) do
		if sector.Guardpost and (not guaranteed_spawn or not table.find(guaranteed_spawn, id)) then
			viableSectors[#viableSectors + 1] = id
		end
	end
	
	local spawned = 0
	local spawnOn = {}
	for i = 0, lMaxStaticSquads do
		if #viableSectors == 0 then break end
	
		local random = BraidRandom(xxhash(Game.id, i), 1, #viableSectors)
		local randomId = table.remove(viableSectors, random)
		spawnOn[#spawnOn + 1] = randomId
	end
	
	for i, sector in ipairs(guaranteed_spawn) do
		spawnOn[#spawnOn + 1] = sector
	end

	local squadDef = EnemySquadDefs["DiamondBriefcase"]
	local squadDefCarrier = squadDef.DiamondBriefcaseCarrier
	assert(squadDefCarrier)
	for i, sectorId in ipairs(spawnOn) do
		-- Check if there is a diamond briefcase here already.
		local _, enemySquads = GetSquadsInSector(sectorId)
		if enemySquads and #enemySquads > 0 then
			for i, sq in ipairs(enemySquads) do
				if sq.diamond_briefcase then
					goto continue
				end
			end
		end
		-- Promote a normal squad to a diamond briefcase squad if one exists here.
		local bestUnit = false
		for i, sq in ipairs(enemySquads) do
			local units = sq.units
			for i, u in ipairs(units) do
				local ud = gv_UnitData[u]
				local template = UnitDataDefs[ud.class]
				if not ud.villain and not template.ImportantNPC then
					bestUnit = ud
					break
				end
			end
			if bestUnit then break end
		end
		
		if not bestUnit then
			local unitIds, unitNames, unitSources, unitAppearance = GenerateRandEnemySquadUnits(squadDef.id)
			local units = GenerateUnitsFromTemplates(sectorId, unitIds, "StaticDB", unitNames, unitAppearance)
			local squad_id = CreateNewSatelliteSquad(
				{
					Side = "enemy1",
					CurrentSector = sectorId,
					Name = squadDef.displayName and _InternalTranslate(squadDef.displayName) or SquadName:GetNewSquadName("enemy1", units),
					diamond_briefcase = true,
					shipment_preset_id = "DiamondShipment",
					enemy_squad_def = squadDef.id,
				},
				units
			)
			for i, s in ipairs(unitSources) do
				if s == squadDefCarrier then
					bestUnit = units[i]
					break
				end
			end
			bestUnit = gv_UnitData[bestUnit]
			assert(bestUnit) -- Diamond briefcase carrier not spawned
		end

		local dbItem = PlaceInventoryItem("DiamondBriefcase")
		dbItem.drop_chance = 100
		dbItem.extra_tag = "dynamic-db"
		bestUnit:AddItem("Inventory", dbItem)

		::continue::
	end
end

GameVar("DynamicDBSquadAccumChance", 0)
GameVar("DynamicDBSquadLastSpawnTime", 0)

function OnMsg.NewDay()
	if gv_SatelliteAttacksHalted then return end

	DynamicDBSquadAccumChance = DynamicDBSquadAccumChance or 0
	DynamicDBSquadLastSpawnTime = DynamicDBSquadLastSpawnTime or 0

	if DynamicDBSquadLastSpawnTime - Game.CampaignTime > const.Scale.day * lDynamicSquadDayCooldown then
		return
	end
	
	local currentDynamicSquadsOnMap = 0
	for i, sq in ipairs(g_SquadsArray) do
		if sq.diamond_briefcase_dynamic then
			currentDynamicSquadsOnMap = currentDynamicSquadsOnMap + 1
		end
	end
	if currentDynamicSquadsOnMap >= lMaxDynamicSquads then return end
	
	DynamicDBSquadAccumChance = DynamicDBSquadAccumChance + lDynamicSquadDayChanceToSpawn
	if DynamicDBSquadAccumChance > InteractionRand(100, "ShipmentRoll") then
		SpawnDynamicDBSquad()
		DynamicDBSquadLastSpawnTime = Game.CampaignTime
		DynamicDBSquadAccumChance = 0
	end
end

function PickShipmentPreset()
	local shipmentPresets = Presets.ShipmentSquadPreset
	
	local weights = {}
	for i, group in ipairs(shipmentPresets) do
		for i, preset in ipairs(group) do
			if EvalConditionList(preset.Conditions) then
				weights[#weights + 1] = { preset.weight, preset.id }
			end
		end
	end
	
	return GetWeightedRandom(weights, xxhash(Game.id, Game.CampaignTime, gv_NextSquadUniqueId))
end

function GetAllShipmentItems()
	local shipmentPresets = Presets.ShipmentSquadPreset

	local items = {}
	for i, group in ipairs(shipmentPresets) do
		for i, preset in ipairs(group) do
			items[#items + 1] = { preset.item, preset.id }
		end
	end
	return items
end

if FirstLoad then
	ShipmentItemsCache = false
end

function OnMsg.DataLoaded()
	ShipmentItemsCache = GetAllShipmentItems()
end

function HasAnyShipmentItem(unit)
	local hasBriefcase, shipmentPresetId = false, false
	for i, itemPair in ipairs(ShipmentItemsCache) do
		hasBriefcase = not not unit:HasItem(itemPair[1])
		if hasBriefcase then
			shipmentPresetId = itemPair[2]
			break
		end
	end
	return hasBriefcase, shipmentPresetId
end


if FirstLoad then
	DBRoutesCacheDynamic = false
	DBRoutesMaxDistanceForLandOnlyCheck = 10
end

if config.Mods then

function OnMsg.NewGame()
	DBRoutesCacheDynamic = false
end

function OnMsg.StartSatelliteGameplay()
	if ModsLoaded and #ModsLoaded > 0 and not DBRoutesCacheDynamic then
		DelayedCall(0, GenerateDynamicDBPathCache) --should only reach this line when loading a save in sat view
	end
end

function OnMsg.GameMetadataLoaded()
	if ModsLoaded and #ModsLoaded > 0 then
		GenerateDynamicDBPathCache()
	end
end

function OnMsg.CampaignStarted()
	if ModsLoaded and #ModsLoaded > 0 then
		GenerateDynamicDBPathCache()
	end
end

end --config.Mods

function SpawnDynamicDBSquad(overrideSourceDest, srcOrDstSectorFilter)
	local routes = DBRoutesCacheDynamic or DBRoutesCacheStatic
	if not routes then return end

	local weights = {}
	if overrideSourceDest then
		local src = overrideSourceDest[1]
		local dst = overrideSourceDest[2]
		if src and dst then
			local route = GenerateRouteDijkstra(src, dst, false, empty_table, nil, nil, "diamonds")
			if route then
				route.source = src
				route.dest = dst
				weights[#weights + 1] = { 100, route }
				routes = empty_table
			else
				return
			end
		end
	end
	
	-- Evaluate route weights.
	for i, route in ipairs(routes) do
		if srcOrDstSectorFilter and route.source ~= srcOrDstSectorFilter and route.dest ~= srcOrDstSectorFilter then
			goto continue
		end
	
		local srcSector = gv_Sectors[route.source]
		local dstSector = gv_Sectors[route.dest]
		if not srcSector.reveal_allowed or srcSector.Side ~= "enemy1" then goto continue end
		if not dstSector.reveal_allowed or dstSector.Side ~= "enemy1" then goto continue end
		if srcSector.no_ddb or dstSector.no_ddb then goto continue end
	
		-- Sector weights depend on total route length, to prevent only the
		-- long routes from getting picked.
		local weightPerSector = MulDivRound(1, 1000, #route)
		local weight = 0
		local playerSectorsAround = {}
		for i, sId in ipairs(route) do
			local prevSector = route[i - 1]
			local nextSector = route[i + 1]
			local sector = gv_Sectors[sId]
			
			-- Prefer routes which graze player sectors.
			if sector.Side ~= "player1" then
				weight = weight + weightPerSector
				ForEachSectorAround(sId, 1, function(sectorAroundId)
					if sId ~= sectorAroundId and sectorAroundId ~= prevSector and sectorAroundId ~= nextSector then
						local sectorAround = gv_Sectors[sectorAroundId]
						if sectorAround.Side == "player1" and not playerSectorsAround[sectorAroundId] then
							playerSectorsAround[sectorAroundId] = true
							playerSectorsAround[#playerSectorsAround + 1] = sectorAroundId
						end
					end
				end)
			else
				weight = weight - 100
			end
		end
		
		local playerSectors = #playerSectorsAround
		if playerSectors <= 2 then
			playerSectors = 0
		end
		
		weight = weight + weightPerSector * playerSectors * 100
		weight = weight + #route * 2 -- Prefer longer routes
		weights[#weights + 1] = { weight, route, playerSectors }
		
		::continue::
	end
	if #weights == 0 then return end
	
	-- Remove bottom worst
	table.sort(weights, function(a, b) return a[1] > b[1] end)
	if #weights > 4 then
		local halfWeights = #weights / 2
		table.iclear(weights, halfWeights)
	end

	local randomRoute = GetWeightedRandom(weights, xxhash(Game.id, Game.CampaignTime, gv_NextSquadUniqueId))
	if not randomRoute then return end
	
	local presetId = PickShipmentPreset() or "DiamondShipment"
	local preset = ShipmentPresets[presetId]
	if not preset then return end
	
	local sectorId = randomRoute.source
	local squadDef = EnemySquadDefs[preset.enemy_squad_def or "DiamondBriefcase"]
	local squadDefCarrier = squadDef.DiamondBriefcaseCarrier
	local unitIds, unitNames, unitSources, unitAppearance = GenerateRandEnemySquadUnits(squadDef.id)
	local units = GenerateUnitsFromTemplates(sectorId, unitIds, "Shipment", unitNames, unitAppearance)
	local carrier = false
	for i, s in ipairs(unitSources) do
		if s == squadDefCarrier then
			carrier = units[i]
		end
	end
	carrier = gv_UnitData[carrier]
	assert(carrier) -- DDiamond briefcase carrier not spawned

	local dbItem = PlaceInventoryItem(preset.item or "DiamondBriefcase")
	dbItem.drop_chance = 100
	dbItem.extra_tag = "dynamic-db"
	carrier:AddItem("Inventory", dbItem)
	
	local squad_id = CreateNewSatelliteSquad(
		{
			Side = "enemy1",
			CurrentSector = sectorId,
			Name = preset.SquadName and _InternalTranslate(preset.SquadName) or SquadName:GetNewSquadName("enemy1", units),
			diamond_briefcase = true,
			diamond_briefcase_dynamic = true,
			shipment_preset_id = presetId,
			always_visible = true,
			enemy_squad_def = squadDef.id,
			image = preset.squad_icon
		},
		units
	)
	
	local squad = gv_Squads[squad_id]
	randomRoute = table.copy(randomRoute)
	randomRoute = {randomRoute} -- Waypointify
	randomRoute.despawn_at_last_sector = true
	randomRoute.diamond_briefcase = true
	SetSatelliteSquadRoute(squad, randomRoute)
end

function GenerateDynamicDBPathCache(save, ged)
	local activeMods = config.Mods and ModsLoaded and #ModsLoaded > 0
	
	if save and activeMods then 
		if ged then
			ged:ShowMessage("Warning", "Stop mods before saving the DB cache as they might cause incorrect generation of routes.")
		end
		return
	end
	
	if activeMods and DBRoutesCacheDynamic then
		return
	end

	PauseInfiniteLoopDetection("DBPathfinding")
	local st = GetPreciseTicks()
	local routeCache = {}
	local sources = {}
	local destinations = {}
	local campaign = GetCurrentCampaignPreset()
	local cols = campaign.sector_columns
	local rows = campaign.sector_rows
	
	--caches for optimizing the GenerateRouteDijkstraSimplified
	local cache_sorted_sectors = {}
	local cache_sectors_shortcuts = {}
	local cache_neighbors = {}
	
	for id, sector in sorted_pairs(gv_Sectors) do
		cache_sorted_sectors[#cache_sorted_sectors + 1] = id
		cache_sectors_shortcuts[#cache_sectors_shortcuts + 1] = GetShortcutsAtSector(id, "force_twoway")
		cache_neighbors[id] = GetNeighborSectors(id)
		
		if IsSectorUnderground(id) then goto continue end
		
		if sector.DBSourceSector and not sources[id] then
			sources[#sources + 1] = id
			sources[id] = "src"
		end
		
		local row, col = sector_unpack(id)
		local isEdgeSector = row == rows or cols == col or row == 1 or col == 1
		if (sector.DBDestinationSector or isEdgeSector) and not destinations[id] then
			destinations[#destinations + 1] = id
			destinations[id] = isEdgeSector and "edge" or "dest"
		end
		
		::continue::
	end
	
	if #sources == 0 or #destinations == 0 then 
		DBRoutesCacheDynamic = {}
		return
	end

	local dedupe = {}
	for i, source in ipairs(sources) do
		for i, dest in ipairs(destinations) do
			if source == dest then goto continue end
			
			local dist = GetSectorDistance(source, dest)
			local r
			if dist <= DBRoutesMaxDistanceForLandOnlyCheck then
				r = GenerateRouteDijkstraSimplified(source, dest, "land_only", "diamonds", cache_sorted_sectors, cache_sectors_shortcuts, cache_neighbors)
			else
				r = GenerateRouteDijkstraSimplified(source, dest, "land_water_boatless", "diamonds", cache_sorted_sectors, cache_sectors_shortcuts, cache_neighbors)
 			end
			if not r then goto continue end
			
			-- Shave off weird looking routes at the edge of the map.
			if destinations[dest] == "edge" then
				local edgeSectorsToRemove = 0
				for i = #r, 1, -1 do
					local sectorId = r[i]
					local row, col = sector_unpack(sectorId)
					local isEdgeSector = row == rows or cols == col or row == 1 or col == 1
					if isEdgeSector then
						edgeSectorsToRemove = edgeSectorsToRemove + 1
					else
						break
					end
				end
				if edgeSectorsToRemove > 1 then
					local routeLength = #r
					for i = 0, edgeSectorsToRemove - 2 do
						r[routeLength - i] = nil
					end
					dest = r[#r]
				end
			end
			
			if dedupe[source .. " " .. dest] then goto continue end
			
			local startSector = source
			local firstSectorInRoute = r[1]
			local sX, sY = sector_unpack(startSector)
			local fX, fY = sector_unpack(firstSectorInRoute)
			assert(abs(sX - fX) == 1 or abs(sY - fY) == 1)

			-- The route should be at least X long.
			if #r >= lMinDynamicSquadRouteLength then
				r.source = source
				r.dest = dest
				dedupe[source .. " " .. dest] = true
				routeCache[#routeCache + 1] = r
			end

			::continue::
		end
	end

	if save then
		local data = {}
		data = routeCache

		local code = TableToLuaCode(data)
		code = "if FirstLoad then \nDBRoutesCacheStatic = " .. code .. "\nend"
		SaveSVNFile("svnProject/Lua/DiamondPaths.generated.lua", code)
	else
		DBRoutesCacheDynamic = routeCache
	end
	--DebugPrint(string.format("GenerateDynamicDBPathCache finished after: %d ms/n", GetPreciseTicks() - st))
	ResumeInfiniteLoopDetection("DBPathfinding")
end

local function pq_parent(i)
	return DivRound(i - 1, 2)
end

local function pq_left_child(i)
	return 2 * i
end

local function pq_right_child(i)
	return 2 * i + 1
end

local function swap(t, i, j, key)
	local tempid = t[i].id
	local tempIdxCache = t[i].idx_in_cache
	local tempWeight = t[i].weight

	t[i].id = t[j].id
	t[i].idx_in_cache = t[j].idx_in_cache
	t[i].weight = t[j].weight
	
	t[j].id = tempid
	t[j].idx_in_cache = tempIdxCache
	t[j].weight = tempWeight
	
	if key then
		t[t[i][key]] = i
		t[t[j][key]] = j
	end
end

local function pq_shift_up(t, i, field, key)
	local parent = t[pq_parent(i)]
	local parent_idx = pq_parent(i)
	while i > 1 and (parent[field] > t[i][field] or (parent[field] == t[i][field] and parent.idx_in_cache > t[i].idx_in_cache and parent_idx ~= 1)) do
		swap(t, parent_idx, i, key)
		i = parent_idx
		parent_idx = pq_parent(i)
		parent = t[parent_idx]
	end
end

local function pq_shift_down(t, i, field, key)
	local curr_idx = i
	local size = t.table_size
	local curr_node = t[curr_idx]
	
	local left_child_idx = pq_left_child(i)
	local left_node = t[left_child_idx]
	if left_child_idx <= size and (left_node[field] < curr_node[field] or (left_node[field] == curr_node[field] and left_node.idx_in_cache < curr_node.idx_in_cache)) then
		curr_idx = left_child_idx
		curr_node = t[curr_idx]
	end
	
	local right_child_idx = pq_right_child(i)
	local right_node = t[right_child_idx]
	if right_child_idx <= size and (right_node[field] < curr_node[field] or (right_node[field] == curr_node[field] and right_node.idx_in_cache < curr_node.idx_in_cache))  then
		curr_idx = right_child_idx
	end
	
	if i ~= curr_idx then
		swap(t, i, curr_idx, key)
		pq_shift_down(t, curr_idx, field, key)
	end
end

function pq_insert(t, node, field, key)
	t.table_size = t.table_size + 1
	local size = t.table_size
	t[size] = node
	t[t[size][key]] = size
	pq_shift_up(t, size, field, key)
end

function pq_pop_max(t, field, key)
	local max_prio_node = t[1]
	local size = t.table_size
	swap(t, 1, size, key)
	t[t[size][key]] = nil
	t[size] = nil
	t.table_size = t.table_size - 1
	pq_shift_down(t, 1, field, key)
	
	return max_prio_node
end

function pq_change_prio(t, i, field, value, key)
	local old_value = t[i][field]
	t[i][field] = value
	
	if value > old_value then
		pq_shift_down(t, i, field, key)
	else
		pq_shift_up(t, i, field, key)
	end
end

function pq_remove(t, i, field, key)
	t[i] = t[1]
	
	pq_shift_up(t, i, field, key)
	pq_pop_max(t, field, key)
end

local function GetMinUnvisitedPathSizeSector(unvisited, sector_path_size)
	local min = max_int
	local min_sector
	local min_sector_idx
	for idx, sector in ipairs(unvisited) do
		local sector_value = sector_path_size[sector]
		if sector and sector_value < min then
			min = sector_value
			min_sector = sector
			min_sector_idx = idx
		end
	end
	if min == max_int then
		return false 
	end
	return min_sector, min_sector_idx
end

function GenerateRouteDijkstraSimplified(start_sector, end_sector, pass_mode, side, cache_sorted_sectors, cache_sectors_shortcuts, cache_neighbors)
	local startIsUnderground = gv_Sectors and gv_Sectors[start_sector] and gv_Sectors[start_sector].GroundSector
	local endIsUnderground = gv_Sectors and gv_Sectors[end_sector] and gv_Sectors[end_sector].GroundSector
	
	assert(not startIsUnderground and not endIsUnderground, "Diamond briefcase routes should start/end on ground sectors.")

	if start_sector == end_sector then
		return false
	end
	
	if GetSectorDistance(start_sector, end_sector) == 1 then
		local dir = GetSectorDirection(start_sector, end_sector)
		local time = GetSectorTravelTime(start_sector, end_sector, nil, nil, pass_mode, nil, side, dir, nil, cache_neighbors[start_sector])
		if time then
			return { end_sector }
		end
	end

	local underground_sector_map = {}
	local priority_queue = {}
	priority_queue.table_size = 0
	local prev = {}
	
	local currIdx
	for idx, sector_id in ipairs(cache_sorted_sectors) do
		if sector_id == start_sector then
			pq_insert(priority_queue, {id = sector_id, weight = 0, idx_in_cache = idx}, "weight", "id")
			currIdx = idx
		else
			pq_insert(priority_queue, {id = sector_id, weight = max_int, idx_in_cache = idx}, "weight", "id")
		end
		
		local sectorPreset = gv_Sectors[sector_id]
		if sectorPreset.GroundSector then
			underground_sector_map[sectorPreset.GroundSector] = sector_id
		end
	end
	
	local curr = start_sector
	while true do
		local currPreset = gv_Sectors[curr]
		local curr_node = priority_queue[1]
		local currentIsUnderground = not not currPreset.GroundSector
		
		for _, dir in ipairs(const.WorldDirections) do
			local neigh = cache_neighbors[curr] and cache_neighbors[curr][dir] or GetNeighborSector(curr, dir)
			if neigh and currentIsUnderground then
				neigh = neigh .. "_Underground"
			end
			
			if priority_queue[neigh] then
				local time = GetSectorTravelTime(curr, neigh, nil, nil, pass_mode, nil, side, dir, cache_sectors_shortcuts[currIdx], cache_neighbors[curr])
				if time then
					local time_value = time + curr_node.weight
					if time_value < priority_queue[priority_queue[neigh]].weight then
						pq_change_prio(priority_queue, priority_queue[neigh], "weight", time_value, "id")
						prev[neigh] = curr
					end
				end
			end
		end
		
		local last_node = pq_pop_max(priority_queue, "weight", "id")
		local new_node = priority_queue[1]
		local weight = new_node and new_node.weight
		if weight and weight ~= max_int then
			curr = new_node.id
			currIdx = new_node.idx_in_cache
		else
			curr = false
		end
		
		if not curr then 
			return false 
		end
		if curr == end_sector then
			local s = curr
			local route_rev = {}
			local water_sectors = 0
			while s ~= start_sector do
				table.insert(route_rev, s)
				s = prev[s]
			end
			
			local reversedRoute = table.reverse(route_rev)
			return reversedRoute
		end
	end
end

function GetStaticDiamondBriefcaseSquadOnSector(sectorId)
	local _, enemySquads = GetSquadsInSector(sectorId)
	if enemySquads and #enemySquads > 0 then
		for i, sq in ipairs(enemySquads) do
			if sq.diamond_briefcase and not sq.diamond_briefcase_dynamic then
				return sq
			end
		end
	end
	return false
end

local function lCheckDiamondBadge()
	local sector = gv_Sectors[gv_CurrentSectorId]
	if not sector then return end
	local hasIntel = sector.intel_discovered
	
	for i, u in ipairs(g_Units) do
		-- Check if the unit has any of the shipment items
		local hasBriefcase, shipmentPresetId = HasAnyShipmentItem(u)
		hasBriefcase = hasBriefcase and (u.team.side == "enemy1" or u.team.side == "enemy2" or u:IsDead())
		local showBriefcase = hasIntel or u:IsDead()
		
		if hasBriefcase and hasIntel then
			local ud = GameState.entering_sector and gv_UnitData[u.session_id]
			local statusEffectObj = ud or u
			statusEffectObj:AddStatusEffect("DiamondCarrier")
		end
		
		local needsBadge = hasBriefcase and showBriefcase
		local diamondBadge = TargetHasBadgeOfPreset("DiamondBadge", u)
		local hasBadge = not not diamondBadge
		
		if needsBadge ~= hasBadge then
			if needsBadge then
				CreateBadgeFromPreset("DiamondBadge", { target = u, spot = u:GetInteractableBadgeSpot() or "Origin" }, u)
			else
				diamondBadge:Done()
			end
		end
		
		local badge = TargetHasBadgeOfPreset("DiamondBadge", u)
		if badge then
			local shipmentPreset = ShipmentPresets[shipmentPresetId or "DiamondShipment"]
			badge.ui.idImageIntel:SetImage(shipmentPreset.intel_icon)
			badge.ui.idImage:SetImage(shipmentPreset.badge_icon)
			badge.ui:SetRolloverTitle(shipmentPreset.IntelTitle)
			badge.ui:SetRolloverText(shipmentPreset.IntelText)
		end
	end
end

OnMsg.CloseSatelliteView = lCheckDiamondBadge
OnMsg.EnterSector = lCheckDiamondBadge
OnMsg.CombatEnd = lCheckDiamondBadge
function OnMsg.InventoryChange(u)
	if not IsKindOf(u, "Unit") and not TargetHasBadgeOfPreset("DiamondBadge", u) then return end
	lCheckDiamondBadge()
end
function OnMsg.IntelDiscovered(sectorId)
	if sectorId ~= gv_CurrentSectorId then return end
	lCheckDiamondBadge()
end