Skip to content

Commit

Permalink
refactor: make ResourceAmount an immutable record
Browse files Browse the repository at this point in the history
  • Loading branch information
raoulvdberge committed Aug 3, 2024
1 parent 5bb69a4 commit a8adc84
Show file tree
Hide file tree
Showing 27 changed files with 102 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ public CraftingPatternClientTooltipComponent(final int width,
this.width = width;
this.height = height;
this.craftingPattern = craftingPattern;
final ItemResource outputResource = craftingPattern.output().getResource() instanceof ItemResource itemResource
final ItemResource outputResource = craftingPattern.output().resource() instanceof ItemResource itemResource
? itemResource
: null;
this.outputStack = outputResource != null
? outputResource.toItemStack(craftingPattern.output().getAmount())
? outputResource.toItemStack(craftingPattern.output().amount())
: null;
this.outputText = outputResource != null
? Component.literal(String.format("%dx ", craftingPattern.output().getAmount()))
? Component.literal(String.format("%dx ", craftingPattern.output().amount()))
.append(outputResource.toItemStack().getHoverName())
.withStyle(ChatFormatting.GRAY) : null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,11 @@ private ItemStack createProcessingPattern() {
final ItemStack result = createPatternStack(PatternType.PROCESSING);
final List<Optional<ResourceAmount>> inputs = new ArrayList<>();
for (int i = 0; i < processingInput.size(); ++i) {
inputs.add(Optional.ofNullable(processingInput.get(i)).map(ResourceAmount::copy));
inputs.add(Optional.ofNullable(processingInput.get(i)));
}
final List<Optional<ResourceAmount>> outputs = new ArrayList<>();
for (int i = 0; i < processingOutput.size(); ++i) {
outputs.add(Optional.ofNullable(processingOutput.get(i)).map(ResourceAmount::copy));
outputs.add(Optional.ofNullable(processingOutput.get(i)));
}
final ProcessingPatternState patternProcessingState = new ProcessingPatternState(
inputs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ public static Optional<ItemStack> getOutput(final ItemStack stack) {
}
return RefinedStorageApi.INSTANCE.getPattern(stack, level).map(pattern -> {
if (pattern instanceof CraftingPattern craftingPattern
&& craftingPattern.output().getResource() instanceof ItemResource itemResource) {
&& craftingPattern.output().resource() instanceof ItemResource itemResource) {
return itemResource.toItemStack();
}
if (pattern instanceof ProcessingPattern processingPattern
&& processingPattern.outputs().size() == 1
&& processingPattern.outputs().getFirst().getResource() instanceof ItemResource itemResource) {
&& processingPattern.outputs().getFirst().resource() instanceof ItemResource itemResource) {
return itemResource.toItemStack();
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ private static List<Component> getOutputText(final ProcessingPatternState state)

private static Component getOutputText(final ResourceAmount resourceAmount) {
final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering(
resourceAmount.getResource()
resourceAmount.resource()
);
final String displayAmount = rendering.getDisplayedAmount(
resourceAmount.getAmount(),
resourceAmount.amount(),
false
);
return Component.literal(String.format("%sx ", displayAmount))
.append(rendering.getDisplayName(resourceAmount.getResource()))
.append(rendering.getDisplayName(resourceAmount.resource()))
.withStyle(ChatFormatting.GRAY);
}

Expand Down Expand Up @@ -113,10 +113,10 @@ private void renderMatrixSlots(final int x,
graphics.blitSprite(SLOT, slotX, slotY, 18, 18);
slots.get(idx).ifPresent(resourceAmount -> {
final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering(
resourceAmount.getResource()
resourceAmount.resource()
);
rendering.render(resourceAmount.getResource(), graphics, slotX + 1, slotY + 1);
AbstractBaseScreen.renderResourceAmount(graphics, slotX + 1, slotY + 1, resourceAmount.getAmount(),
rendering.render(resourceAmount.resource(), graphics, slotX + 1, slotY + 1);
AbstractBaseScreen.renderResourceAmount(graphics, slotX + 1, slotY + 1, resourceAmount.amount(),
rendering);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ protected AbstractGridContainerMenu(
this.active = gridData.active();

final GridViewBuilder viewBuilder = createViewBuilder();
gridData.resources().forEach(gridResource -> viewBuilder.withResource(
gridResource.resourceAmount().getResource(),
gridResource.resourceAmount().getAmount(),
gridResource.trackedResource().orElse(null)
gridData.resources().forEach(resource -> viewBuilder.withResource(
resource.resourceAmount().resource(),
resource.resourceAmount().amount(),
resource.trackedResource().orElse(null)
));

this.view = viewBuilder.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ static <T extends ResourceKey> StorageData<T> ofSameTypeStorage(
? Optional.of(limitedStorage.getCapacity())
: Optional.empty();
final List<StorageResource<T>> resources = storage.getAll().stream()
.filter(resourceAmount -> valid.test(resourceAmount.getResource()))
.filter(resourceAmount -> valid.test(resourceAmount.resource()))
.map(resourceAmount -> getResource(storage, caster, resourceAmount))
.toList();
return new StorageData<>(capacity, resources);
Expand All @@ -79,8 +79,8 @@ private static <T extends ResourceKey> StorageResource<T> getResource(
final ResourceAmount resourceAmount
) {
return new StorageResource<>(
caster.apply(resourceAmount.getResource()),
resourceAmount.getAmount(),
caster.apply(resourceAmount.resource()),
resourceAmount.amount(),
getChanged(storage, resourceAmount)
);
}
Expand All @@ -90,7 +90,7 @@ private static Optional<StorageChangedByAt> getChanged(final Storage storage,
if (!(storage instanceof TrackedStorage trackedStorage)) {
return Optional.empty();
}
return trackedStorage.findTrackedResourceByActorType(resourceAmount.getResource(), PlayerActor.class)
return trackedStorage.findTrackedResourceByActorType(resourceAmount.resource(), PlayerActor.class)
.map(StorageChangedByAt::ofTrackedResource);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public List<TrackedResourceAmount> getResources(final Class<? extends Actor> act
final RootStorage rootStorage = storage.getRootStorage();
return rootStorage.getAll().stream().map(resource -> new TrackedResourceAmount(
resource,
rootStorage.findTrackedResourceByActorType(resource.getResource(), actorType).orElse(null)
rootStorage.findTrackedResourceByActorType(resource.resource(), actorType).orElse(null)
)).toList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,15 +250,15 @@ private List<ClientTooltipComponent> getResourceSlotHelpTooltip(final ItemStack
resourceSlot.getPrimaryResourceFactory().create(carried).ifPresent(primaryResourceInstance -> lines.add(
MouseClientTooltipComponent.resource(
MouseClientTooltipComponent.Type.LEFT,
primaryResourceInstance.getResource(),
primaryResourceInstance.resource(),
null
)
));
for (final ResourceFactory alternativeResourceFactory : resourceSlot.getAlternativeResourceFactories()) {
final var result = alternativeResourceFactory.create(carried);
result.ifPresent(alternativeResourceInstance -> lines.add(MouseClientTooltipComponent.resource(
MouseClientTooltipComponent.Type.RIGHT,
alternativeResourceInstance.getResource(),
alternativeResourceInstance.resource(),
null
)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public final class ResourceCodecs {
.codec()
.dispatch(PlatformResourceKey::getResourceType, ResourceType::getMapCodec);
public static final Codec<ResourceAmount> AMOUNT_CODEC = RecordCodecBuilder.create(instance -> instance.group(
CODEC.fieldOf("resource").forGetter(resourceAmount -> (PlatformResourceKey) resourceAmount.getResource()),
Codec.LONG.fieldOf("amount").forGetter(ResourceAmount::getAmount)
CODEC.fieldOf("resource").forGetter(resourceAmount -> (PlatformResourceKey) resourceAmount.resource()),
Codec.LONG.fieldOf("amount").forGetter(ResourceAmount::amount)
).apply(instance, ResourceAmount::new));
public static final Codec<Optional<ResourceAmount>> AMOUNT_OPTIONAL_CODEC = AMOUNT_CODEC.optionalFieldOf("resource")
.codec();
Expand All @@ -64,12 +64,12 @@ public void encode(final RegistryFriendlyByteBuf buf, final PlatformResourceKey
};
public static final StreamCodec<RegistryFriendlyByteBuf, ResourceAmount> AMOUNT_STREAM_CODEC = StreamCodec.of(
(buf, resourceAmount) -> {
final ResourceKey resourceKey = resourceAmount.getResource();
final ResourceKey resourceKey = resourceAmount.resource();
if (!(resourceKey instanceof PlatformResourceKey platformResourceKey)) {
throw new DecoderException("Cannot encode non-platform resource key");
}
STREAM_CODEC.encode(buf, platformResourceKey);
buf.writeLong(resourceAmount.getAmount());
buf.writeLong(resourceAmount.amount());
},
buf -> {
final PlatformResourceKey resourceKey = STREAM_CODEC.decode(buf);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public long getAmount(final int index) {
if (slot == null) {
return 0;
}
return slot.getResourceAmount().getAmount();
return slot.getResourceAmount().amount();
}

@Override
Expand All @@ -116,7 +116,7 @@ public void setAmount(final int index, final long amount) {
if (slot == null) {
return;
}
final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(slot.getResourceAmount().getResource()));
final long newAmount = MathUtil.clamp(amount, 0, getMaxAmount(slot.getResourceAmount().resource()));
if (newAmount == 0) {
remove(index);
} else {
Expand Down Expand Up @@ -190,7 +190,7 @@ public Set<ResourceKey> getUniqueResources() {
if (slot == null) {
continue;
}
result.add(slot.getResourceAmount().getResource());
result.add(slot.getResourceAmount().resource());
}
return result;
}
Expand All @@ -203,7 +203,7 @@ public List<ResourceKey> getResources() {
if (slot == null) {
continue;
}
result.add(slot.getResourceAmount().getResource());
result.add(slot.getResourceAmount().resource());
}
return result;
}
Expand Down Expand Up @@ -290,7 +290,7 @@ public long insert(final ResourceKey resource, final long amount, final Action a
final ResourceAmount slot = get(i);
if (slot == null) {
remainder -= insertIntoEmptySlot(i, platformResource, action, remainder);
} else if (slot.getResource().equals(resource)) {
} else if (slot.resource().equals(resource)) {
remainder -= insertIntoExistingSlot(
i,
platformResource,
Expand Down Expand Up @@ -322,7 +322,7 @@ private long insertIntoExistingSlot(final int slotIndex,
final Action action,
final long amount,
final ResourceAmount existing) {
final long spaceRemaining = resource.getInterfaceExportLimit() - existing.getAmount();
final long spaceRemaining = resource.getInterfaceExportLimit() - existing.amount();
final long inserted = Math.min(spaceRemaining, amount);
if (action == Action.EXECUTE) {
grow(slotIndex, inserted);
Expand All @@ -335,11 +335,11 @@ public long extract(final ResourceKey resource, final long amount, final Action
long extracted = 0;
for (int i = 0; i < size(); ++i) {
final ResourceAmount slotContents = get(i);
if (slotContents == null || !resource.equals(slotContents.getResource())) {
if (slotContents == null || !resource.equals(slotContents.resource())) {
continue;
}
final long stillNeeded = amount - extracted;
final long toExtract = Math.min(slotContents.getAmount(), stillNeeded);
final long toExtract = Math.min(slotContents.amount(), stillNeeded);
if (action == Action.EXECUTE) {
shrink(i, toExtract);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class ResourceContainerSlot {

ResourceContainerSlot(final ResourceAmount resourceAmount) {
this.resourceAmount = resourceAmount;
this.stackRepresentation = resourceAmount.getResource() instanceof ItemResource itemResource
? itemResource.toItemStack(resourceAmount.getAmount())
this.stackRepresentation = resourceAmount.resource() instanceof ItemResource itemResource
? itemResource.toItemStack(resourceAmount.amount())
: ItemStack.EMPTY;
}

Expand All @@ -23,15 +23,15 @@ ResourceAmount getResourceAmount() {
}

PlatformResourceKey getPlatformResource() {
return (PlatformResourceKey) resourceAmount.getResource();
return (PlatformResourceKey) resourceAmount.resource();
}

ItemStack getStackRepresentation() {
return stackRepresentation;
}

ResourceContainerSlot withAmount(final long newAmount) {
return new ResourceContainerSlot(new ResourceAmount(resourceAmount.getResource(), newAmount));
return new ResourceContainerSlot(new ResourceAmount(resourceAmount.resource(), newAmount));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public int getWidth(final Font font) {

@Override
public void renderImage(final Font font, final int x, final int y, final GuiGraphics graphics) {
RefinedStorageApi.INSTANCE.getResourceRendering(resourceAmount.getResource()).render(
resourceAmount.getResource(),
RefinedStorageApi.INSTANCE.getResourceRendering(resourceAmount.resource()).render(
resourceAmount.resource(),
graphics,
x,
y
Expand All @@ -50,10 +50,10 @@ public void renderImage(final Font font, final int x, final int y, final GuiGrap

private static Component getNameWithAmount(final ResourceAmount resourceAmount) {
final ResourceRendering rendering = RefinedStorageApi.INSTANCE.getResourceRendering(
resourceAmount.getResource()
resourceAmount.resource()
);
final String amount = rendering.getDisplayedAmount(resourceAmount.getAmount(), true);
final Component displayName = rendering.getDisplayName(resourceAmount.getResource());
final String amount = rendering.getDisplayedAmount(resourceAmount.amount(), true);
final Component displayName = rendering.getDisplayName(resourceAmount.resource());
if (amount.isEmpty()) {
return displayName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ public Optional<FluidOperationResult> drainContainer(final ItemStack container)
@Override
public Optional<FluidOperationResult> fillContainer(final ItemStack container,
final ResourceAmount resourceAmount) {
if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) {
if (!(resourceAmount.resource() instanceof FluidResource fluidResource)) {
return Optional.empty();
}
final SimpleSingleStackStorage interceptingStorage = new SimpleSingleStackStorage(container);
Expand All @@ -186,7 +186,7 @@ public Optional<FluidOperationResult> fillContainer(final ItemStack container,
return Optional.empty();
}
try (Transaction tx = Transaction.openOuter()) {
final long inserted = storage.insert(toFluidVariant(fluidResource), resourceAmount.getAmount(), tx);
final long inserted = storage.insert(toFluidVariant(fluidResource), resourceAmount.amount(), tx);
return Optional.of(new FluidOperationResult(
interceptingStorage.getStack(),
fluidResource,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ private StorageViewImpl(final int index) {
public long extract(final FluidVariant resource, final long maxAmount, final TransactionContext transaction) {
final ResourceAmount resourceAmount = resourceContainer.get(index);
if (resourceAmount == null
|| !(resourceAmount.getResource() instanceof FluidResource fluidResource)
|| !(resourceAmount.resource() instanceof FluidResource fluidResource)
|| !resource.equals(toFluidVariant(fluidResource))) {
return 0;
}
final long extracted = Math.min(maxAmount, resourceAmount.getAmount());
final long extracted = Math.min(maxAmount, resourceAmount.amount());
if (extracted > 0) {
updateSnapshots(transaction);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ void attach(final RootStorage rootStorage, final boolean replay) {
rootStorage.addListener(listener);
if (replay) {
rootStorage.getAll().forEach(resourceAmount -> watcher.onChanged(
resourceAmount.getResource(),
resourceAmount.getAmount(),
resourceAmount.resource(),
resourceAmount.amount(),
rootStorage.findTrackedResourceByActorType(
resourceAmount.getResource(),
resourceAmount.resource(),
actorType
).orElse(null)
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ public Optional<FluidOperationResult> drainContainer(final ItemStack container)
@Override
public Optional<FluidOperationResult> fillContainer(final ItemStack container,
final ResourceAmount resourceAmount) {
if (!(resourceAmount.getResource() instanceof FluidResource fluidResource)) {
if (!(resourceAmount.resource() instanceof FluidResource fluidResource)) {
return Optional.empty();
}
return FluidUtil.getFluidHandler(container).map(handler -> {
final FluidStack fluidStack = toFluidStack(fluidResource, resourceAmount.getAmount());
final FluidStack fluidStack = toFluidStack(fluidResource, resourceAmount.amount());
final long filled = handler.fill(fluidStack, IFluidHandler.FluidAction.EXECUTE);
return new FluidOperationResult(handler.getContainer(), fluidResource, filled);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ public int getTanks() {
@Override
public FluidStack getFluidInTank(final int tank) {
final ResourceAmount resourceAmount = container.get(tank);
if (resourceAmount == null || !(resourceAmount.getResource() instanceof FluidResource fluidResource)) {
if (resourceAmount == null || !(resourceAmount.resource() instanceof FluidResource fluidResource)) {
return FluidStack.EMPTY;
}
return toFluidStack(fluidResource, resourceAmount.getAmount());
return toFluidStack(fluidResource, resourceAmount.amount());
}

@Override
Expand Down
Loading

0 comments on commit a8adc84

Please sign in to comment.