diff --git a/Construct [BP]/scripts/classes/Builder/Builder.js b/Construct [BP]/scripts/classes/Builder/Builder.js index afadf1e..300a144 100644 --- a/Construct [BP]/scripts/classes/Builder/Builder.js +++ b/Construct [BP]/scripts/classes/Builder/Builder.js @@ -1,6 +1,9 @@ import { BuilderOptions } from "./BuilderOptions"; export class Builder { + playerId; + materialInstanceName = void 0; + constructor(playerId) { this.playerId = playerId; } diff --git a/Construct [BP]/scripts/classes/Instance/StructureInstance.js b/Construct [BP]/scripts/classes/Instance/StructureInstance.js index 76d7738..7cc9693 100644 --- a/Construct [BP]/scripts/classes/Instance/StructureInstance.js +++ b/Construct [BP]/scripts/classes/Instance/StructureInstance.js @@ -5,12 +5,14 @@ import { Structure } from "../Structure/Structure"; import { InstanceOptions } from "./InstanceOptions"; import { TicksPerSecond } from "@minecraft/server"; import { InstanceNotPlacedError } from "../Errors/InstanceNotPlacedError"; +import { StructureMaterials } from "../Materials/StructureMaterials"; export class StructureInstance { options; structure = void 0; verifier = void 0; outliner = void 0; + materials = void 0; constructor(instanceName, structureId) { this.structure = new Structure(structureId); @@ -25,6 +27,7 @@ export class StructureInstance { delete this.structure; delete this.outliner; delete this.verifier; + delete this.materials; } refreshBox() { @@ -34,8 +37,11 @@ export class StructureInstance { this.outliner = new StructureOutliner(this); if (!this.verifier) this.verifier = new StructureVerifier(this, { isEnabled: this.options.verifier.isEnabled, trackPlayerDistance: this.options.verifier.trackPlayerDistance }); + if (!this.materials) + this.materials = new StructureMaterials(this); this.outliner.refresh(); this.verifier.refresh(); + this.materials.refresh(); } getName() { @@ -134,6 +140,10 @@ export class StructureInstance { return this.structure.getAllLocations(); } + getActiveMaterials() { + return this.materials; + } + isEnabled() { return this.options.isEnabled; } @@ -177,8 +187,8 @@ export class StructureInstance { } place(dimensionId, worldLocation) { - this.move(dimensionId, worldLocation); this.enable(); + this.move(dimensionId, worldLocation); } move(dimensionId, worldLocation) { diff --git a/Construct [BP]/scripts/classes/Materials/MaterialCounter.js b/Construct [BP]/scripts/classes/Materials/MaterialCounter.js deleted file mode 100644 index 1cb2aec..0000000 --- a/Construct [BP]/scripts/classes/Materials/MaterialCounter.js +++ /dev/null @@ -1,78 +0,0 @@ -class MaterialCounter { - instance - materials; - - constructor(instance) { - this.instance = instance; - this.materials = {}; - } - - populateAll() { - for (const layer = 0; layer < this.instance.getMaxLayer(); layer++) - this.getLayer(layer) - } - - populateLayer(layer) { - for (const block of this.instance.getLayerBlocks(layer)) - this.countBlock(block) - } - - populateActive() { - for (const block of this.instance.getActiveBlocks()) - this.countBlock(block) - } - - countBlock(block) { - const itemStack = block?.getItemStack(); - const typeId = itemStack?.typeId; - if (!typeId) return; - if (!this.materials[typeId]) - this.materials[typeId] = { count: 0, stackSize: itemStack.maxAmount }; - this.materials[typeId].count++; - } - - clear() { - this.materials = {}; // does this leak memory?? - } - - toString() { - const materials = {}; - for (const block of this.instance.getAllBlocks()) { - const itemStack = block?.getItemStack(); - const typeId = itemStack?.typeId.replace('minecraft:', ''); - if (!typeId) continue; - if (!materials[typeId]) { - materials[typeId] = { count: 0, maxStack: itemStack.maxAmount }; - } - materials[typeId].count++; - } - let message = []; - for (const blockType in materials) { - let count = materials[blockType].count; - let countStr = ''; - const maxStack = materials[blockType].maxStack; - const fullShulker = 27 * maxStack; - if (count >= fullShulker) { - countStr = `${Math.floor(count / fullShulker)} sb`; - } - if (count > fullShulker) { - countStr += ' + '; - } - count %= fullShulker; - if (count >= maxStack) { - countStr += `${Math.floor(count / maxStack)} stack`; - } - if (count > maxStack) { - countStr += ' + '; - } - count %= maxStack; - if (count > 0) { - countStr += count; - } - message.push(` ${blockType}: ${countStr}`); - } - return message.sort().join('\n'); - } -} - -export { MaterialCounter }; \ No newline at end of file diff --git a/Construct [BP]/scripts/classes/Materials/MaterialsForm.js b/Construct [BP]/scripts/classes/Materials/MaterialsForm.js new file mode 100644 index 0000000..6245af6 --- /dev/null +++ b/Construct [BP]/scripts/classes/Materials/MaterialsForm.js @@ -0,0 +1,37 @@ +import { MaterialsFormBuilder } from './MaterialsFormBuilder'; +import { forceShow } from '../../utils'; +import { Builders } from '../Builder/Builders'; +import { structureCollection } from '../Structure/StructureCollection'; + +export class MaterialsForm { + constructor(player) { + this.player = player; + this.show(); + } + + show() { + try { + return forceShow(this.player, MaterialsFormBuilder.buildInstanceSelector(this.player)).then((response) => { + if (response.canceled) + return; + const selectedInstanceName = structureCollection.getInstanceNames()[response.selection]; + if (selectedInstanceName) { + this.setActiveInstance(selectedInstanceName); + this.player.sendMessage(`§7Selected instance for material grabber: §2${selectedInstanceName}`); + return; + } + }); + } catch (e) { + if (e.message === 'Menu timed out.') { + this.player.sendMessage('§8Menu timed out.'); + return; + } + throw e; + } + } + + setActiveInstance(instanceName) { + const builder = Builders.get(this.player.id); + builder.materialInstanceName = instanceName; + } +} \ No newline at end of file diff --git a/Construct [BP]/scripts/classes/Materials/MaterialsFormBuilder.js b/Construct [BP]/scripts/classes/Materials/MaterialsFormBuilder.js new file mode 100644 index 0000000..c5efc8f --- /dev/null +++ b/Construct [BP]/scripts/classes/Materials/MaterialsFormBuilder.js @@ -0,0 +1,25 @@ +import { ActionFormData } from "@minecraft/server-ui"; +import { MenuFormBuilder } from "../MenuFormBuilder"; +import { structureCollection } from "../Structure/StructureCollection"; +import { Builders } from "../Builder/Builders"; + +export class MaterialsFormBuilder { + static menuTitle = MenuFormBuilder.menuTitle + ' Material Grabber'; + + static buildInstanceSelector(player) { + const allInstanceNameForm = new ActionFormData() + .title(this.menuTitle); + const currInstanceName = Builders.get(player.id).materialInstanceName; + let body = '§7Current instance: '; + if (currInstanceName) + body += `§2${currInstanceName}`; + else + body += '§7None'; + body += '\n§7Select an instance:'; + allInstanceNameForm.body(body); + structureCollection.getInstanceNames().forEach(instanceName => { + allInstanceNameForm.button(`§2${instanceName}`); + }); + return allInstanceNameForm; + } +} \ No newline at end of file diff --git a/Construct [BP]/scripts/classes/Materials/StructureMaterials.js b/Construct [BP]/scripts/classes/Materials/StructureMaterials.js new file mode 100644 index 0000000..b981844 --- /dev/null +++ b/Construct [BP]/scripts/classes/Materials/StructureMaterials.js @@ -0,0 +1,102 @@ +class StructureMaterials { + instance; + materials; + + constructor(instance) { + this.instance = instance; + this.materials = {}; + } + + refresh() { + this.clear(); + this.populateInstance(); + } + + populateInstance() { + try { + if (this.instance.hasLocation()) + this.populateActive(); + else + this.populateAll(); + } catch (e) { + if (e.name === 'InstanceNotPlacedError') + this.clear(); + else + throw e; + } + } + + get(itemType) { + return this.materials[itemType]; + } + + isEmpty() { + return Object.keys(this.materials).length === 0; + } + + has(itemType) { + return this.materials[itemType] !== undefined; + } + + remove(itemType, amount) { + if (!this.materials[itemType]) return; + this.materials[itemType].count -= amount; + if (this.materials[itemType].count <= 0) + delete this.materials[itemType]; + } + + populateAll() { + for (let layer = 0; layer < this.instance.getMaxLayer(); layer++) + this.populateLayer(layer) + } + + populateLayer(layer) { + for (const block of this.instance.getLayerBlocks(layer)) + this.countBlock(block) + } + + populateActive() { + for (const block of this.instance.getActiveBlocks()) + this.countBlock(block) + } + + countBlock(block) { + const itemStack = block?.getItemStack(); + const typeId = itemStack?.typeId; + if (!typeId) return; + if (!this.materials[typeId]) + this.materials[typeId] = { count: 0, stackSize: itemStack.maxAmount }; + this.materials[typeId].count++; + } + + clear() { + for (const key in this.materials) + delete this.materials[key]; + } + + toString() { + let message = []; + for (const blockType in this.materials) { + let count = this.materials[blockType].count; + let countStr = ''; + const stackSize = this.materials[blockType].stackSize; + const fullShulker = 27 * stackSize; + if (count >= fullShulker) + countStr = `${Math.floor(count / fullShulker)} sb`; + if (count > fullShulker) + countStr += ' + '; + count %= fullShulker; + if (count >= stackSize) + countStr += `${Math.floor(count / stackSize)} stack`; + if (count > stackSize) + countStr += ' + '; + count %= stackSize; + if (count > 0) + countStr += count; + message.push(` ${blockType}: ${countStr}`); + } + return message.sort().join('\n'); + } +} + +export { StructureMaterials }; \ No newline at end of file diff --git a/Construct [BP]/scripts/classes/MenuForm.js b/Construct [BP]/scripts/classes/MenuForm.js index a70eb45..5931019 100644 --- a/Construct [BP]/scripts/classes/MenuForm.js +++ b/Construct [BP]/scripts/classes/MenuForm.js @@ -59,7 +59,14 @@ export class MenuForm { const structureId = await this.getStructureId(); if (!structureId) return; - structureCollection.add(instanceName, structureId); + try { + structureCollection.add(instanceName, structureId); + } catch (e) { + if (e.name === 'InvalidInstanceError') { + this.player.sendMessage(`§cInstance '${instanceName}' already exists. Try again with a new name.`); + return void 0; + } + } return instanceName; }); } diff --git a/Construct [BP]/scripts/options/materialGrabber.js b/Construct [BP]/scripts/options/materialGrabber.js index e11fec3..b7ab95e 100644 --- a/Construct [BP]/scripts/options/materialGrabber.js +++ b/Construct [BP]/scripts/options/materialGrabber.js @@ -1,19 +1,168 @@ import { BuilderOption } from '../classes/Builder/BuilderOption'; -import { world } from '@minecraft/server'; +import { EntityComponentTypes, ItemStack, Player, world, system } from '@minecraft/server'; +import { MaterialsForm } from '../classes/Materials/MaterialsForm'; +import { Builders } from '../classes/Builder/Builders'; +import { structureCollection } from '../classes/Structure/StructureCollection'; const builderOption = new BuilderOption({ identifier: 'materialGrabber', displayName: 'Material Grabber', description: 'Pulls structure items from inventories.', - howToUse: "Interact with inventories using a paper named 'Material Grabber' to pull structure items from them.", + howToUse: "Interact with inventories using an item named 'Material Grabber' to pull structure items from them.", }); +world.beforeEvents.itemUse.subscribe(onItemUse); world.beforeEvents.playerInteractWithBlock.subscribe(onPlayerInteract); world.beforeEvents.playerInteractWithEntity.subscribe(onPlayerInteract); +function onItemUse(event) { + if (!isActionItem(event.itemStack) || !builderOption.isEnabled(event.source.id)) + return; + event.cancel = true; + system.run(() => new MaterialsForm(event.source)); +} + function onPlayerInteract(event) { - // get inventory - // analyze active structure items if not analyzed -- there needs to be a way to refresh this that is efficient - // find items in inventory that match items in structure - // transfer to player + if (!isActionItem(event.itemStack) || !builderOption.isEnabled(event.player.id)) + return; + const player = event.player; + const target = event.block || event.target; + if (target instanceof Player) + return; + const materials = getActiveMaterials(player); + if (!materials) + return; + const targetContainer = target.getComponent(EntityComponentTypes.Inventory)?.container; + if (!targetContainer || materials.isEmpty()) + return; + event.cancel = true; + system.run(() => transferMaterialsToPlayer(player, targetContainer, materials)); +} + +function isActionItem(itemStack) { + return itemStack?.nameTag === 'Material Grabber'; +} + +function getActiveMaterials(player) { + const focusedInstanceName = Builders.get(player.id).materialInstanceName; + if (!focusedInstanceName) + return void 0; + const structure = structureCollection.get(focusedInstanceName); + if (!structure) + return void 0; + return structure.getActiveMaterials(); +} + +function transferMaterialsToPlayer(player, targetContainer, materials) { + const playerContainer = player.getComponent(EntityComponentTypes.Inventory)?.container; + if (!playerContainer) + return; + ignoreAlreadyGathered(materials, playerContainer); + let transferCount = 0; + for (let slotIndex = 0; slotIndex < targetContainer.size; slotIndex++) { + const slot = targetContainer.getSlot(slotIndex); + transferCount += tryTransferToPlayer(slot, playerContainer, materials); + } + sendTransferMessage(player, transferCount); + materials.refresh(); +} + +function ignoreAlreadyGathered(materials, playerContainer) { + for (let slotIndex = 0; slotIndex < playerContainer.size; slotIndex++) { + const slot = playerContainer.getSlot(slotIndex); + if (slot.hasItem()) { + materials.remove(slot.typeId, slot.amount); + } + } +} + +function sendTransferMessage(player, transferCount) { + if (transferCount === 0) { + player.onScreenDisplay.setActionBar('§7Grabbed 0 items.'); + } else if (transferCount === 1) { + player.onScreenDisplay.setActionBar('§aGrabbed 1 item.'); + } else { + player.onScreenDisplay.setActionBar(`§aGrabbed ${transferCount} item(s).`); + } +} + +function tryTransferToPlayer(slot, playerContainer, materials) { + if (slot.hasItem() && materials.has(slot.typeId)) { + const grabAmount = Math.min(slot.amount, materials.get(slot.typeId).count); + if (grabAmount > 0) + return tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount); + } + return 0; +} + +function tryTransferAmountToPlayer(slot, playerContainer, materials, grabAmount) { + const itemStack = slot.getItem(); + if (canAddItem(playerContainer, itemStack)) { + const itemStackToAdd = new ItemStack(itemStack.typeId, grabAmount); + addItem(playerContainer, itemStackToAdd); + materials.remove(itemStack.typeId, grabAmount); + removeAmount(slot, grabAmount); + return grabAmount; + } + return 0; +} + +function removeAmount(slot, amount) { + if (amount === slot.amount) { + slot.setItem(void 0); + } else { + slot.amount -= amount; + slot.setItem(slot.getItem()); + } +} + +function canAddItem(inventory, itemStack) { + if (inventory.emptySlotsCount !== 0) return true; + for (let i = 0; i < inventory.size; i++) { + const slot = inventory.getSlot(i); + if (itemFitsInPartiallyFilledSlot(slot, itemStack)) return true; + } + return false; +} + +function itemFitsInPartiallyFilledSlot(slot, itemStack) { + return slot.hasItem() && slot.isStackableWith(itemStack) && slot.amount + itemStack.amount <= slot.maxAmount; +} + +function addItem(inventory, itemStack) { + const isItemDeposited = partiallyFilledSlotPass(inventory, itemStack); + if (!isItemDeposited) + emptySlotPass(inventory, itemStack); + +} + +function partiallyFilledSlotPass(inventory, itemStack) { + for (let slotNum = 0; slotNum < inventory.size; slotNum++) { + const slot = inventory.getSlot(slotNum); + if (isSlotAvailableForStacking(slot, itemStack)) { + const remainderAmount = Math.max(0, (slot.amount + itemStack.amount) - slot.maxAmount); + slot.amount += itemStack.amount - remainderAmount; + if (remainderAmount > 0) { + const remainderStack = new ItemStack(itemStack.typeId, remainderAmount); + addItem(inventory, remainderStack); + } + return true; + } + } + return false; +} + +function emptySlotPass(inventory, itemStack) { + for (let slotNum = 0; slotNum < inventory.size; slotNum++) { + const slot = inventory.getSlot(slotNum); + if (!slot.hasItem()) { + slot.setItem(itemStack); + return true; + } + } + return false; +} + +function isSlotAvailableForStacking(slot, itemStack) { + return slot.hasItem() && slot.isStackableWith(itemStack) && slot.amount !== slot.maxAmount; } \ No newline at end of file diff --git a/README.md b/README.md index 63d238a..3b9f8dc 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Give yourself the tools to ease the survival building process with Construct: an - **Block Validation**: Highlights incorrectly placed blocks. - **Easy Place**: Always places blocks correctly. +- **Material Grabbing**: Pulls the required materials from chests in just one click. - **Layered Display**: Build structures in layers. - **Structure Management**: Create and edit many structures at once. @@ -52,7 +53,7 @@ Shows the construct form. Only available while **Canopy** is installed. - [x] Structure naming & movement - [x] Easyplace - [x] Correct block placement checking -- [ ] Automatic material gathering from inventories +- [x] Automatic material gathering from inventories - [ ] Structure Mirroring & Rotation - [ ] Structure Merging into SuperStructures