-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathBuildSimulator.kt
More file actions
880 lines (764 loc) · 36.5 KB
/
BuildSimulator.kt
File metadata and controls
880 lines (764 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/*
* Copyright 2025 Lambda
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambda.interaction.construction.simulation
import com.lambda.config.groups.BuildConfig
import com.lambda.config.groups.InteractionConfig
import com.lambda.context.SafeContext
import com.lambda.interaction.construction.blueprint.Blueprint
import com.lambda.interaction.construction.context.BreakContext
import com.lambda.interaction.construction.context.InteractionContext
import com.lambda.interaction.construction.context.PlaceContext
import com.lambda.interaction.construction.processing.PreProcessingInfo
import com.lambda.interaction.construction.processing.ProcessorRegistry.getProcessingInfo
import com.lambda.interaction.construction.result.BreakResult
import com.lambda.interaction.construction.result.BuildResult
import com.lambda.interaction.construction.result.InteractResult
import com.lambda.interaction.construction.result.PlaceResult
import com.lambda.interaction.construction.verify.TargetState
import com.lambda.interaction.material.ContainerSelection.Companion.selectContainer
import com.lambda.interaction.material.StackSelection
import com.lambda.interaction.material.StackSelection.Companion.select
import com.lambda.interaction.material.StackSelection.Companion.selectStack
import com.lambda.interaction.material.container.ContainerManager.containerWithMaterial
import com.lambda.interaction.material.container.MaterialContainer
import com.lambda.interaction.request.breaking.BreakConfig
import com.lambda.interaction.request.inventory.InventoryConfig
import com.lambda.interaction.request.placing.PlaceConfig
import com.lambda.interaction.request.rotating.Rotation.Companion.rotation
import com.lambda.interaction.request.rotating.Rotation.Companion.rotationTo
import com.lambda.interaction.request.rotating.RotationConfig
import com.lambda.interaction.request.rotating.RotationManager
import com.lambda.interaction.request.rotating.RotationRequest
import com.lambda.interaction.request.rotating.visibilty.PlaceDirection
import com.lambda.interaction.request.rotating.visibilty.VisibilityChecker.CheckedHit
import com.lambda.interaction.request.rotating.visibilty.VisibilityChecker.getVisibleSurfaces
import com.lambda.interaction.request.rotating.visibilty.VisibilityChecker.scanSurfaces
import com.lambda.interaction.request.rotating.visibilty.lookAt
import com.lambda.interaction.request.rotating.visibilty.lookAtBlock
import com.lambda.interaction.request.rotating.visibilty.lookInDirection
import com.lambda.module.modules.client.TaskFlowModule
import com.lambda.threading.runSafe
import com.lambda.util.BlockUtils
import com.lambda.util.BlockUtils.blockState
import com.lambda.util.BlockUtils.calcItemBlockBreakingDelta
import com.lambda.util.BlockUtils.hasFluid
import com.lambda.util.BlockUtils.instantBreakable
import com.lambda.util.BlockUtils.isEmpty
import com.lambda.util.BlockUtils.isNotEmpty
import com.lambda.util.Communication.warn
import com.lambda.util.math.distSq
import com.lambda.util.math.vec3d
import com.lambda.util.player.SlotUtils.hotbar
import com.lambda.util.player.copyPlayer
import com.lambda.util.player.gamemode
import com.lambda.util.world.WorldUtils.isLoaded
import com.lambda.util.world.raycast.RayCastUtils.blockResult
import net.minecraft.block.BlockState
import net.minecraft.block.FallingBlock
import net.minecraft.block.OperatorBlock
import net.minecraft.block.SlabBlock
import net.minecraft.block.Waterloggable
import net.minecraft.block.enums.SlabType
import net.minecraft.block.pattern.CachedBlockPosition
import net.minecraft.enchantment.Enchantments
import net.minecraft.fluid.FlowableFluid
import net.minecraft.fluid.LavaFluid
import net.minecraft.fluid.WaterFluid
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
import net.minecraft.item.ItemPlacementContext
import net.minecraft.item.ItemStack
import net.minecraft.item.ItemUsageContext
import net.minecraft.state.property.Properties
import net.minecraft.util.Hand
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.util.math.Vec3d
import net.minecraft.util.shape.VoxelShapes
import kotlin.math.pow
object BuildSimulator {
fun Blueprint.simulate(
eye: Vec3d,
interactionConfig: InteractionConfig = TaskFlowModule.interaction,
rotation: RotationConfig = TaskFlowModule.rotation,
inventory: InventoryConfig = TaskFlowModule.inventory,
build: BuildConfig = TaskFlowModule.build,
) = runSafe {
structure.entries.flatMap { (pos, target) ->
val preProcessing = target.getProcessingInfo(pos) ?: return@flatMap emptySet()
checkRequirements(pos, target, build).let {
if (it.isEmpty()) return@let
return@flatMap it
}
checkPostProcessResults(pos, eye, preProcessing, target, interactionConfig, build.placing, rotation, inventory).let {
if (it.isEmpty()) return@let
return@flatMap it
}
checkPlaceResults(pos, eye, preProcessing, target, build.placing, interactionConfig, rotation, inventory).let {
if (it.isEmpty()) return@let
return@flatMap it
}
checkBreakResults(pos, eye, preProcessing, build.breaking, interactionConfig, rotation, inventory, build).let {
if (it.isEmpty()) return@let
return@flatMap it
}
warn("Nothing matched $pos $target")
emptySet()
}.toSet()
} ?: emptySet()
private fun SafeContext.checkRequirements(
pos: BlockPos,
target: TargetState,
build: BuildConfig
): Set<BuildResult> {
val acc = mutableSetOf<BuildResult>()
/* the chunk is not loaded */
if (!isLoaded(pos)) {
acc.add(BuildResult.ChunkNotLoaded(pos))
return acc
}
val state = blockState(pos)
/* block is already in the correct state */
if (target.matches(state, pos, world)) {
acc.add(BuildResult.Done(pos))
return acc
}
/* block should be ignored */
if (state.block in build.breaking.ignoredBlocks && target.type == TargetState.Type.AIR) {
acc.add(BuildResult.Ignored(pos))
return acc
}
/* the player is in the wrong game mode to alter the block state */
if (player.isBlockBreakingRestricted(world, pos, gamemode)) {
acc.add(BuildResult.Restricted(pos))
return acc
}
/* the player has no permissions to alter the block state */
if (state.block is OperatorBlock && !player.isCreativeLevelTwoOp) {
acc.add(BuildResult.NoPermission(pos, state))
return acc
}
/* block is outside the world so it cant be altered */
if (!world.worldBorder.contains(pos) || world.isOutOfHeightLimit(pos)) {
acc.add(BuildResult.OutOfWorld(pos))
return acc
}
/* block is unbreakable, so it cant be broken or replaced */
if (state.getHardness(world, pos) < 0 && !gamemode.isCreative) {
acc.add(BuildResult.Unbreakable(pos, state))
return acc
}
return acc
}
private fun SafeContext.checkPostProcessResults(
pos: BlockPos,
eye: Vec3d,
preProcessing: PreProcessingInfo,
targetState: TargetState,
interactionConfig: InteractionConfig,
place: PlaceConfig,
rotation: RotationConfig,
inventory: InventoryConfig
): Set<BuildResult> {
if (targetState !is TargetState.State) return emptySet()
val acc = mutableSetOf<BuildResult>()
val state = blockState(pos)
if (!targetState.matches(state, pos, world, preProcessing.ignore))
return acc
val interactBlock: (BlockState, Set<Direction>?, Item?, Boolean) -> Unit =
interactBlock@{ expectedState, sides, item, placing ->
val boxes = state.getOutlineShape(world, pos).boundingBoxes.map { it.offset(pos) }
val validHits = mutableListOf<CheckedHit>()
val blockedHits = mutableSetOf<Vec3d>()
val misses = mutableSetOf<Vec3d>()
val airPlace = placing && place.airPlace.isEnabled
boxes.forEach { box ->
val refinedSides = if (interactionConfig.checkSideVisibility) {
box.getVisibleSurfaces(eye).let { visibleSides ->
sides?.let { specific ->
visibleSides.intersect(specific)
} ?: visibleSides.toSet()
}
} else sides ?: Direction.entries.toSet()
scanSurfaces(
box,
refinedSides,
interactionConfig.resolution,
preProcessing.surfaceScan
) { hitSide, vec ->
val distSquared = eye distSq vec
if (distSquared > interactionConfig.interactReach.pow(2)) {
misses.add(vec)
return@scanSurfaces
}
val newRotation = eye.rotationTo(vec)
val hit = if (interactionConfig.strictRayCast) {
val rayCast = newRotation.rayCast(interactionConfig.interactReach, eye)
when {
rayCast != null && (!airPlace || eye distSq rayCast.pos <= distSquared) ->
rayCast.blockResult
airPlace -> {
val hitVec = newRotation.castBox(box, interactionConfig.interactReach, eye)
BlockHitResult(hitVec, hitSide, pos, false)
}
else -> null
}
} else {
val hitVec = newRotation.castBox(box, interactionConfig.interactReach, eye)
BlockHitResult(hitVec, hitSide, pos, false)
} ?: return@scanSurfaces
val checked = CheckedHit(hit, newRotation, interactionConfig.interactReach)
if (hit.blockResult?.blockPos != pos) {
blockedHits.add(vec)
return@scanSurfaces
}
validHits.add(checked)
}
}
if (validHits.isEmpty()) {
if (misses.isNotEmpty()) {
acc.add(BuildResult.OutOfReach(pos, eye, misses))
} else {
//ToDo: Must clean up surface scan usage / renders. Added temporary direction until changes are made
acc.add(
BuildResult.NotVisible(
pos,
pos,
Direction.UP,
eye.distanceTo(pos.offset(Direction.UP).vec3d)
)
)
}
return@interactBlock
}
interactionConfig.pointSelection.select(validHits)?.let { checkedHit ->
val checkedResult = checkedHit.hit
val rotationTarget = lookAt(checkedHit.targetRotation, 0.001)
val context = InteractionContext(
checkedResult.blockResult ?: return@interactBlock,
RotationRequest(rotationTarget, rotation),
player.inventory.selectedSlot,
state,
expectedState
)
val stackSelection = (item ?: player.mainHandStack.item).select()
val hotbarCandidates = selectContainer {
matches(stackSelection) and ofAnyType(MaterialContainer.Rank.HOTBAR)
}.let { predicate ->
stackSelection.containerWithMaterial(inventory, predicate)
}
if (hotbarCandidates.isEmpty()) {
acc.add(
BuildResult.WrongItemSelection(
pos,
context,
stackSelection,
player.mainHandStack,
inventory
)
)
return@interactBlock
} else {
context.hotbarIndex =
player.hotbar.indexOf(hotbarCandidates.first().matchingStacks(stackSelection).first())
}
acc.add(InteractResult.Interact(pos, context))
}
}
val mismatchedProperties = state.properties.filter { state.get(it) != targetState.blockState.get(it) }
mismatchedProperties.forEach { property ->
when (property) {
Properties.EYE -> {
if (state.get(Properties.EYE)) return@forEach
val expectedState = state.with(Properties.EYE, true)
interactBlock(expectedState, null, null, false)
}
Properties.INVERTED -> {
val expectedState = state.with(Properties.INVERTED, !state.get(Properties.INVERTED))
interactBlock(expectedState, null, null, false)
}
Properties.DELAY -> {
val expectedState =
state.with(Properties.DELAY, state.cycle(Properties.DELAY).get(Properties.DELAY))
interactBlock(expectedState, null, null, false)
}
Properties.COMPARATOR_MODE -> {
val expectedState = state.with(
Properties.COMPARATOR_MODE,
state.cycle(Properties.COMPARATOR_MODE).get(Properties.COMPARATOR_MODE)
)
interactBlock(expectedState, null, null, false)
}
Properties.OPEN -> {
val expectedState = state.with(Properties.OPEN, !state.get(Properties.OPEN))
interactBlock(expectedState, null, null, false)
}
Properties.SLAB_TYPE -> {
if (targetState.blockState.get(Properties.SLAB_TYPE) != SlabType.DOUBLE) return@forEach
checkPlaceResults(
pos,
eye,
preProcessing,
targetState,
place,
interactionConfig,
rotation,
inventory
).let { placeResults ->
acc.addAll(placeResults)
}
}
}
}
if (acc.isEmpty()) {
acc.add(BuildResult.Done(pos))
}
return acc
}
private fun SafeContext.checkPlaceResults(
pos: BlockPos,
eye: Vec3d,
preProcessing: PreProcessingInfo,
targetState: TargetState,
place: PlaceConfig,
interactionConfig: InteractionConfig,
rotation: RotationConfig,
inventory: InventoryConfig
): Set<BuildResult> {
val acc = mutableSetOf<BuildResult>()
val currentState = blockState(pos)
val statePromoting = currentState.block is SlabBlock
&& targetState.matches(currentState, pos, world, preProcessing.ignore)
// If the target state is air then the only possible blocks it could place are to remove liquids so we use the Solid TargetState
val nextTargetState = if (targetState is TargetState.Air) {
if (currentState.hasFluid) TargetState.Solid
else return acc
} else if (targetState.isEmpty()) {
// Otherwise if the target state is empty, there's no situation where placement would be required so we can return
return acc
} else targetState
// For example, slabs count as state promoting because you are placing another block to promote the current state to the target state
if (!currentState.isReplaceable && !statePromoting) return acc
preProcessing.sides.forEach { neighbor ->
val hitPos = if (!place.airPlace.isEnabled && (currentState.isEmpty || statePromoting))
pos.offset(neighbor)
else pos
val hitSide = neighbor.opposite
val voxelShape = blockState(hitPos).getOutlineShape(world, hitPos).let { outlineShape ->
if (!outlineShape.isEmpty || !place.airPlace.isEnabled) outlineShape
else VoxelShapes.fullCube()
}
if (voxelShape.isEmpty) return@forEach
val boxes = voxelShape.boundingBoxes.map { it.offset(hitPos) }
val verify: CheckedHit.() -> Boolean = {
hit.blockResult?.blockPos == hitPos && hit.blockResult?.side == hitSide
}
val validHits = mutableListOf<CheckedHit>()
val misses = mutableSetOf<Vec3d>()
val reachSq = interactionConfig.interactReach.pow(2)
boxes.forEach { box ->
val sides = if (interactionConfig.checkSideVisibility) {
box.getVisibleSurfaces(eye).intersect(setOf(hitSide))
} else setOf(hitSide)
scanSurfaces(box, sides, interactionConfig.resolution, preProcessing.surfaceScan) { _, vec ->
val distSquared = eye distSq vec
if (distSquared > reachSq) {
misses.add(vec)
return@scanSurfaces
}
val newRotation = eye.rotationTo(vec)
val hit = if (interactionConfig.strictRayCast) {
val rayCast = newRotation.rayCast(interactionConfig.interactReach, eye)
when {
rayCast != null && (!place.airPlace.isEnabled || eye distSq rayCast.pos <= distSquared) ->
rayCast.blockResult
place.airPlace.isEnabled -> {
val hitVec = newRotation.castBox(box, interactionConfig.interactReach, eye)
BlockHitResult(hitVec, hitSide, hitPos, false)
}
else -> null
}
} else {
val hitVec = newRotation.castBox(box, interactionConfig.interactReach, eye)
BlockHitResult(hitVec, hitSide, hitPos, false)
} ?: return@scanSurfaces
val checked = CheckedHit(hit, newRotation, interactionConfig.interactReach)
if (!checked.verify()) return@scanSurfaces
validHits.add(checked)
}
}
if (validHits.isEmpty()) {
if (misses.isNotEmpty()) {
acc.add(BuildResult.OutOfReach(pos, eye, misses))
return@forEach
}
acc.add(BuildResult.NotVisible(pos, hitPos, hitSide, eye.distanceTo(hitPos.offset(hitSide).vec3d)))
return@forEach
}
interactionConfig.pointSelection.select(validHits)?.let { checkedHit ->
val optimalStack = nextTargetState.getStack(world, pos, inventory)
// ToDo: For each hand and sneak or not?
val fakePlayer = copyPlayer(player).apply {
this.rotation = RotationManager.serverRotation
}
val checkedResult = checkedHit.hit
// ToDo: Override the stack used for this to account for blocks where replaceability is dependent on the held item
val usageContext = ItemUsageContext(
fakePlayer,
Hand.MAIN_HAND,
checkedResult.blockResult,
)
val cachePos = CachedBlockPosition(
usageContext.world, usageContext.blockPos, false
)
val canBePlacedOn = optimalStack.canPlaceOn(cachePos)
if (!player.abilities.allowModifyWorld && !canBePlacedOn) {
acc.add(PlaceResult.IllegalUsage(pos))
return@forEach
}
var context = ItemPlacementContext(usageContext)
if (context.blockPos != pos) {
acc.add(PlaceResult.UnexpectedPosition(pos, context.blockPos))
return@forEach
}
if (!optimalStack.item.isEnabled(world.enabledFeatures)) {
acc.add(PlaceResult.BlockFeatureDisabled(pos, optimalStack))
return@forEach
}
if (!context.canPlace() && !statePromoting) {
acc.add(PlaceResult.CantReplace(pos, context))
return@forEach
}
val blockItem = optimalStack.item as? BlockItem ?: run {
acc.add(PlaceResult.NotItemBlock(pos, optimalStack))
return@forEach
}
context = blockItem.getPlacementContext(context)
?: run {
acc.add(PlaceResult.ScaffoldExceeded(pos, context))
return@forEach
}
lateinit var resultState: BlockState
var rot = fakePlayer.rotation
val simulatePlaceState = placeState@{
resultState = blockItem.getPlacementState(context)
?: return@placeState PlaceResult.BlockedByEntity(pos)
return@placeState if (!nextTargetState.matches(resultState, pos, world, preProcessing.ignore))
PlaceResult.NoIntegrity(
pos,
resultState,
context,
(nextTargetState as? TargetState.State)?.blockState
)
else null
}
val currentDirIsValid = simulatePlaceState()?.let { basePlaceResult ->
if (!place.rotateForPlace) {
acc.add(basePlaceResult)
return@forEach
}
false
} != false
run rotate@{
if (!place.axisRotate) {
fakePlayer.rotation = checkedHit.targetRotation
simulatePlaceState()?.let { rotatedPlaceResult ->
acc.add(rotatedPlaceResult)
return@forEach
}
rot = fakePlayer.rotation
return@rotate
}
fakePlayer.rotation = player.rotation
if (simulatePlaceState() == null) {
rot = fakePlayer.rotation
return@rotate
}
PlaceDirection.entries.asReversed().forEachIndexed direction@{ index, direction ->
fakePlayer.rotation = direction.rotation
when (val placeResult = simulatePlaceState()) {
is PlaceResult.BlockedByEntity -> {
acc.add(placeResult)
return@forEach
}
is PlaceResult.NoIntegrity -> {
if (index != PlaceDirection.entries.lastIndex) return@direction
acc.add(placeResult)
return@forEach
}
else -> {
rot = fakePlayer.rotation
return@rotate
}
}
}
}
val blockHit = checkedResult.blockResult ?: return@forEach
val hitBlock = blockState(blockHit.blockPos).block
val shouldSneak = hitBlock::class in BlockUtils.interactionBlocks
val rotationRequest = if (place.axisRotate) {
lookInDirection(PlaceDirection.fromRotation(rot))
} else lookAt(rot, 0.001)
val placeContext = PlaceContext(
blockHit,
RotationRequest(rotationRequest, rotation),
player.inventory.selectedSlot,
context.blockPos,
blockState(context.blockPos),
resultState,
shouldSneak,
false,
currentDirIsValid
)
val selection = optimalStack.item.select()
val containerSelection = selectContainer { ofAnyType(MaterialContainer.Rank.HOTBAR) }
val container = selection.containerWithMaterial(inventory, containerSelection).firstOrNull() ?: run {
acc.add(
BuildResult.WrongItemSelection(
pos,
placeContext,
optimalStack.item.select(),
player.mainHandStack,
inventory
)
)
return acc
}
val stack = selection.filterStacks(container.stacks).run {
firstOrNull { player.inventory.getSlotWithStack(it) == player.inventory.selectedSlot }
?: first()
}
placeContext.hotbarIndex = player.inventory.getSlotWithStack(stack)
acc.add(PlaceResult.Place(pos, placeContext))
}
}
return acc
}
private fun SafeContext.checkBreakResults(
pos: BlockPos,
eye: Vec3d,
preProcessing: PreProcessingInfo,
breaking: BreakConfig,
interactionConfig: InteractionConfig,
rotation: RotationConfig,
inventory: InventoryConfig,
build: BuildConfig
): Set<BuildResult> {
val acc = mutableSetOf<BuildResult>()
val state = blockState(pos)
/* is a block that will be destroyed by breaking adjacent blocks */
if (!breaking.breakWeakBlocks && state.block.hardness == 0f && state.isNotEmpty) {
acc.add(BuildResult.Ignored(pos))
return acc
}
/* player is standing on top of the block */
if (breaking.avoidSupporting) player.supportingBlockPos.orElse(null)?.let { support ->
if (support != pos) return@let
acc.add(BreakResult.PlayerOnTop(pos, state))
return acc
}
/* liquid needs to be submerged first to be broken */
if (!state.fluidState.isEmpty && state.isReplaceable) {
val submerge = checkPlaceResults(pos, eye, preProcessing, TargetState.Solid, build.placing, interactionConfig, rotation, inventory)
acc.add(BreakResult.Submerge(pos, state, submerge))
acc.addAll(submerge)
return acc
}
if (breaking.avoidLiquids) {
val affectedBlocks = hashSetOf(pos)
val checkQueue = hashSetOf(pos)
while (checkQueue.isNotEmpty()) {
val checkPos = checkQueue.first()
checkQueue.remove(checkPos)
for (offset in Direction.entries) {
val adjacentPos = checkPos.offset(offset)
if (blockState(adjacentPos).block !is FallingBlock) continue
if (adjacentPos in affectedBlocks) continue
if (offset == Direction.UP || FallingBlock.canFallThrough(blockState(adjacentPos.down()))) {
checkQueue.add(adjacentPos)
affectedBlocks.add(adjacentPos)
}
}
}
val affectedFluids = affectedBlocks.fold(hashMapOf<BlockPos, BlockState>()) { accumulator, affectedPos ->
Direction.entries.forEach { offset ->
if (offset == Direction.DOWN) return@forEach
val offsetPos = affectedPos.offset(offset)
val offsetState = blockState(offsetPos)
val fluidState = offsetState.fluidState
val fluid = fluidState.fluid
if (fluidState.isEmpty || fluid !is FlowableFluid) return@forEach
if (offset == Direction.UP) {
accumulator[offsetPos] = offsetState
return@fold accumulator
}
if (offsetState.block is Waterloggable && !fluidState.isEmpty) {
accumulator[offsetPos] = offsetState
return@fold accumulator
}
val levelDecreasePerBlock =
when (fluid) {
is WaterFluid -> fluid.getLevelDecreasePerBlock(world)
is LavaFluid -> fluid.getLevelDecreasePerBlock(world)
else -> 0
}
if (fluidState.level - levelDecreasePerBlock > 0) {
accumulator[offsetPos] = offsetState
return@fold accumulator
}
}
return@fold accumulator
}
if (affectedFluids.isNotEmpty()) {
acc.add(BreakResult.BlockedByFluid(pos, state))
return acc
}
}
val currentRotation = RotationManager.activeRotation
val currentCast = currentRotation.rayCast(interactionConfig.interactReach, eye)
val voxelShape = state.getOutlineShape(world, pos)
voxelShape.getClosestPointTo(eye).ifPresent {
// ToDo: Use closest point of shape of only visible faces
}
val boxes = voxelShape.boundingBoxes.map { it.offset(pos) }
val verify: CheckedHit.() -> Boolean = {
hit.blockResult?.blockPos == pos
}
// ToDo: Move this to a location where more of the context parameters can be properly set
/* the player is buried inside the block */
if (boxes.any { it.contains(eye) }) {
currentCast?.blockResult?.let { blockHit ->
val rotationRequest = RotationRequest(
lookAtBlock(pos, config = interactionConfig), rotation
)
val breakContext = BreakContext(
blockHit,
rotationRequest,
player.inventory.selectedSlot,
StackSelection.EVERYTHING.select(),
instantBreakable(state, pos, breaking.breakThreshold),
state,
breaking.sorter
)
acc.add(BreakResult.Break(pos, breakContext))
return acc
}
}
val validHits = mutableListOf<CheckedHit>()
val misses = mutableSetOf<Vec3d>()
val reachSq = interactionConfig.interactReach.pow(2)
boxes.forEach { box ->
val sides = if (interactionConfig.checkSideVisibility) {
box.getVisibleSurfaces(eye).intersect(Direction.entries)
} else Direction.entries.toSet()
// ToDo: Rewrite Rotation request system to allow support for all sim features and use the rotation finder
scanSurfaces(box, sides, interactionConfig.resolution) { side, vec ->
if (eye distSq vec > reachSq) {
misses.add(vec)
return@scanSurfaces
}
val newRotation = eye.rotationTo(vec)
val hit = if (interactionConfig.strictRayCast) {
newRotation.rayCast(interactionConfig.interactReach, eye)?.blockResult
} else {
val hitVec = newRotation.castBox(box, interactionConfig.interactReach, eye)
BlockHitResult(hitVec, side, pos, false)
} ?: return@scanSurfaces
val checked = CheckedHit(hit, newRotation, interactionConfig.interactReach)
if (!checked.verify()) return@scanSurfaces
validHits.add(checked)
}
}
if (validHits.isEmpty()) {
// ToDo: If we can only mine exposed surfaces we need to add not visible result here
acc.add(BuildResult.OutOfReach(pos, eye, misses))
return acc
}
val bestHit = interactionConfig.pointSelection.select(validHits) ?: return acc
val blockHit = bestHit.hit.blockResult ?: return acc
val target = lookAt(bestHit.targetRotation, 0.001)
val rotationRequest = RotationRequest(target, rotation)
val instant = instantBreakable(state, pos, breaking.breakThreshold)
val breakContext = BreakContext(
blockHit,
rotationRequest,
player.inventory.selectedSlot,
StackSelection.EVERYTHING.select(),
instant,
state,
breaking.sorter
)
if (gamemode.isCreative) {
acc.add(BreakResult.Break(pos, breakContext))
return acc
}
val stackSelection = selectStack(
sorter = compareByDescending<ItemStack> {
it.canBreak(CachedBlockPosition(world, pos, false))
}.thenByDescending {
state.calcItemBlockBreakingDelta(player, world, pos, it)
}
) {
run {
if (breaking.suitableToolsOnly) isSuitableForBreaking(state)
else StackSelection.EVERYTHING
} and if (breaking.forceSilkTouch) {
hasEnchantment(Enchantments.AQUA_AFFINITY)
} else if (breaking.forceFortunePickaxe) {
hasEnchantment(Enchantments.FORTUNE, breaking.minFortuneLevel)
} else StackSelection.EVERYTHING
}
val silentSwapSelection = selectContainer {
ofAnyType(MaterialContainer.Rank.HOTBAR)
}
val swapCandidates = stackSelection.containerWithMaterial(inventory, silentSwapSelection)
if (swapCandidates.isEmpty()) {
acc.add(BuildResult.WrongItemSelection(pos, breakContext, stackSelection, player.mainHandStack, inventory))
return acc
}
val swapStack = swapCandidates.map { it.matchingStacks(stackSelection) }
.asSequence()
.flatten()
.let { containerStacks ->
var bestStack = ItemStack.EMPTY
var bestBreakDelta = -1f
containerStacks.forEach { stack ->
val breakDelta = state.calcItemBlockBreakingDelta(player, world, pos, stack)
if (breakDelta > bestBreakDelta ||
(stack == player.mainHandStack && breakDelta >= bestBreakDelta)
) {
bestBreakDelta = breakDelta
bestStack = stack
}
}
bestStack
}
breakContext.apply {
hotbarIndex = player.hotbar.indexOf(swapStack)
itemSelection = stackSelection
instantBreak = instantBreakable(
state,
pos,
if (breaking.swapMode.isEnabled()) swapStack else player.mainHandStack,
breaking.breakThreshold
)
}
acc.add(BreakResult.Break(pos, breakContext))
return acc
}
}